Definition and usage of substring and substrin js

  • 2020-03-30 02:47:55
  • OfStack

1. The substring method

Definition and usage

The substring method is used to extract the characters of a string mediation between two specified subscripts.

grammar

StringObject. Substring (start, stop)

Parameter         describe
Start      A necessity. A non-negative integer that specifies the position in the stringObject of the first character of the substring to be extracted.
Stop        Optional. A non-negative integer, one more than the position of the last character of the substring to be extracted in the stringObject. If you omit this parameter, the returned substring will go all the way to the end of the string.

The return value

A new string whose value contains a substring of stringObject that contains all characters from start to stop-1, with a length of stop minus start.

instructions

      The substring method returns a substring that includes the character at start, but not the character at end.
      If start is equal to end, the method returns an empty string (that is, a string of length 0).
      If start is larger than end, the method exchanges the two parameters before extracting the substring.
      If start or end is negative, it will be replaced with 0.

2. The substr method

Definition and usage

The substr method returns a substring of the specified length starting at the specified location.

grammar

StringObject. Substr (start [, length])

Parameter         describe
Start      A necessity. The starting position of the desired substring. The index of the first character in a string is 0.
Length    Optional. The number of characters to include in the returned substring.

instructions

If the length is 0 or negative, an empty string is returned.
If this parameter is not specified, the substring continues to the end of the stringObject.

Example 3.


    <script type="text/javascript">  
        function Demo(){   
            var str,str;          
            var s = "Hello Word";   

            str = s.substring(0, 3); //Take the substring.  
            console.log(str);//=====>Hel  

            str = s.substr(0,3);  
            console.log(str);//=====>Hel  
        }  
    </script>  
    


Related articles: