Javascript Substring() Returning The Wrong Value From My String?
I have this code:
var sequence = $stateParams.testId.length == 14 ?
parseInt($stateParams.testId.substring(11, 2)) : 0;
What I expect is for the sequence to be set to 01 (the last two numbers). But what happens is that it returns 198.
Can someone explain why this is?
console.log($stateParams.testId) // "01198-05282-01"
console.log(sequence) // 198
Answer
String#substring
works with the indexes.
The signature of the substring
is
str.substring(indexStart[, indexEnd])
Note that the second parameter is the index itself and not the length of the substring.
If
indexStart
is greater thanindexEnd
, then the effect ofsubstring()
is as if the two arguments were swapped; for example,str.substring(1, 0) == str.substring(0, 1)
.
So,
.substring(11, 2)
is equivalent to .substring(11, 2)
which will give the substring "198-05282-"
and using parseInt()
on it will give the output as 198
.
- Use the second param as index, here, 14(12 + 2)
- Use the radix parameter to
parseInt
as 10 to avoid unexpected results
Code:
var str = '01198-05282-01';
var sequence = str.length == 14 ?
parseInt(str.substring(12, 14), 10) : 0;
// ^^ ^^
console.log(sequence);
To get the substring using the length
, use String#substr
str.substr(12, 2)
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM