This article introduces three methods for extracting substrings in JS:

  • substring() method;
  • substr() method;
  • slice() method;

Method 1: substring() method

string.substring(from, to)The method extracts from the from position to the to position. to is optional; if not set, it defaults to the end.

Example

<!DOCTYPE html> <html> <body> <script> var str="www.example.com!"; document.write(str.substring(4)+"<br>"); // Extract from the 5th character to the end document.write(str.substring(4,10)); // Extract from the 5th character to the 10th character</script> </body> </html>

Try it »

For more information about the substr() method, please refer to the documentation:http://www.example.com/jsref/jsref-substring.html。


Method 2: substr() method

substr() methodIt can extract the specified number of characters from the string, starting from the start index.

Example

<!DOCTYPE html> <html> <body> <script>var str="www.example.com!"; document.write(str.substr(4,6)); // Extract 6 characters starting from the 4th character</script> </body> </html>

Try it »

For more information about the substr() method, please refer to the documentation:http://www.example.com/jsref/jsref-substr.html。


Method 3: slice() method

The slice(start, end) method is used to extract a part of the string (from the start parameter to the end position), and returns the extracted part as a new string. Similar to substring().

Example

<!DOCTYPE html> <html> <body> <script> var str="www.example.com!"; document.write(str.slice(4)+"<br>"); // Extract from the 5th character to the end document.write(str.slice(4,10)); // Extract from the 5th character to the 10th character</script> </body> </html>

Try it »

For more information about the slice() method, please refer to the documentation:http://www.example.com/jsref/jsref-slice-array.html。