How to use String substr() to get substring in Javascript
Get substring
substr()
returns a substring and accepts
either one or two arguments.
The first argument is the starting position. The second argument tells where to stop in term of the number of characters to return. If the second argument is omitted, it is default to the ending of the string.
substr()
does not alter the value of the string itself.
Example
var stringValue = "hello world";
/*www. j a v a 2 s.c o m*/
console.log(stringValue.substr(3)); //"lo world"
console.log(stringValue.substr(3, 7)); //"lo worl"
The code above generates the following result.
Example 2
A negative first argument does the sub string from the end. A negative second number is converted to 0.
var stringValue = "hello world";
//from w ww . j ava 2 s. c o m
console.log(stringValue.substr(-3)); //"rld"
console.log(stringValue.substr(3, -4)); //"" (empty string)
The code above generates the following result.