JavaScript Substring of a String
To find substring of a string in JavaScript, call substring() method on this string and pass the start index and end index as arguments.
Syntax
The syntax to use substring() method on this string str
, with start index startIndex
and end index endIndex
is
str.substring(startIndex, endIndex)
substring() returns a new string with the contents of the original string from position startIndex
upto position endIndex
. Original string remains as is.
Examples
In the following example, we take a string str
and find the substring that spans from index 3
upto index 10
.
index.html
<!DOCTYPE html> <html lang="en"> <body> <pre id="output"></pre> <script> var str = 'hello world'; var startIndex = 3; var endIndex = 10; var result = str.substring(startIndex, endIndex); var output = ''; output += 'Original String : ' + str; output += '\n\nSubstring : ' + result; document.getElementById('output').innerHTML = output; </script> </body> </html>
Conclusion
In this JavaScript Tutorial, we learned how to find substring of a string in JavaScript, using substring() method, with examples.