Home >Web Front-end >JS Tutorial >How to intercept a string in javascript
How to intercept strings in javascript: 1. Use the substr() function to intercept the specified number of characters starting from the specified subscript in the string; 2. Use the substring() function to intercept the string intermediary The character between the two specified subscripts.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.
Method 1: Use substr()
<script type="text/javascript"> var str="Hello world!"; console.log(str); console.log(str.substr(3,9)); //从倒数第六个字符开始,截取四位 </script>
Rendering:
The substr() method can extract the specified number of characters starting from the start subscript in the string.
Syntax:
substr(start,length)
start: The starting subscript of the substring to be intercepted must be a numerical value. If negative, this parameter is the position from the end of the string. That is to say, -1 refers to the last character in the string, -2 refers to the second to last character, and so on. You must write
length: the characters in the substring Number must be a numerical value. If this parameter is not filled in, the characters from the beginning to the end of the string are returned. If length is 0 or negative, an empty string will be returned.
Example:
Method 2: Use substring()
<script type="text/javascript"> var str="Hello world!"; console.log(str); console.log(str.substring(3,9)); //从第三个字符开始到第八位 </script>
Rendering:
The substring() method is used to extract the characters between two specified subscripts in the string.
Syntax:
substring(start,stop)
start: a non-negative integer, which refers to the first character of the substring to be extracted. Position in the string, required element
#stop: a non-negative integer, 1 more than the position of the last character of the substring to be extracted on the string, optional You can write it or not. If you do not write it, the returned substring will go to the end of the string.
The length of the string is stop-start
If the parameters start and If stop is equal, the method returns an empty string. If start is greater than stop, the method will exchange the two parameters before extracting the substring.
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of How to intercept a string in javascript. For more information, please follow other related articles on the PHP Chinese website!