JavaScript string object entry instance of the substring method (for intercepting strings)

  • 2020-03-30 04:09:32
  • OfStack

JavaScript is the substring method

The substring method is used to intercept the string and return the truncated part of the string by specifying the start and end positions. The syntax is as follows:


str_object.substring(start, end)

parameter instructions
str_object String (object) to manipulate
start A necessity. Start intercepting the position of a non-negative integer
end Optional. String truncation end position, non - negative integer; If omitted, until the end of the string

Tip: if the parameter start is equal to end, the method returns an empty string. If start is larger than end, the method exchanges the two arguments before intercepting the string.

Instance of the substring method


<script language="JavaScript"> var str = "abcdef";
document.write( str.substring(1, 3) + "<br />" );
document.write( str.substring(2, 2) + "<br />" );
document.write(str.substring(3, 1)); </script>

Run the example and output:

bc bc

The difference between substring and slice and substr

1. Substring cannot accept negative arguments, whereas (link: #) methods can
2. The second parameter of substring is to specify the position where the interception ends, while the second parameter of (link: #) method is to specify the length of the string interception


Related articles: