Javascript String substring()
gets a sub string from a longer string.
The substring()
method can accept one or two arguments.
str.substring(indexStart[, indexEnd])
indexStart
- the index of the first character to include.indexEnd
- Optional, the index of the first character to exclude.The indexStart
is starting position.
The indexEnd
, if used, indicates where the operation should stop.
This indexEnd
is the position before which capture is stopped.
All characters up to this point are included except the character at that point.
If the second argument is omitted, it is assumed that the ending position is the length of the string.
The substring()
method does not alter the string itself.
It returns a string value as the result, leaving the original unchanged.
let stringValue = "hello world"; console.log(stringValue.substring(3)); // "lo world" console.log(stringValue.substring(3,7)); // "lo w"
For the substring()
method, all negative numbers are converted to 0.
let stringValue = "hello world"; console.log(stringValue.substring(3, -4)); // "hel" console.log(stringValue.substring(-3)); // "hello world"
Uses the substring()
method and length
property to extract the last characters of a particular string.
let anyString = 'Javascript' let a = anyString.substring(anyString.length - 4) console.log(a)//from ww w .j av a 2s .c o m anyString = 'www.java2s.com' a = anyString.substring(anyString.length - 5) console.log(a)