Home >Web Front-end >JS Tutorial >How to use substring method
substring() is a built-in function in JavaScript that can be used to get a substring from a string and return a new substring based on the given parameters. Its usage syntax is such as "string.substring(indexA , [indexB])”.
The operating environment of this article: Windows 7 system, Dell G3 computer, javascript version 1.8.5.
substring() is a built-in function in JavaScript, which is used to obtain substrings from strings. In this article, we will take a detailed look at the usage of substring.
Let’s take a look at the basic syntax of substring first
string.substring(indexA, [indexB])
indexA - an integer between 0 and 1, less than the length of the string.
indexB (optional) - an integer between 0 and the length of the string.
The substring method returns a new substring based on the given parameters.
Let’s look at a specific example
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> // 将字符串作为变量 var string = "sghxdysgcghd"; a = string.substring(0, 4) b = string.substring(1, 6) c = string.substring(5) d = string.substring(0) // 输出新的字符串 // 给定字符串的一部分 document.write(a + "<br>"); document.write(b + "<br>"); document.write(c + "<br>"); document.write(d + "<br>"); </script> </body> </html>
The display effect on the browser is as follows:
Indices always start with 0. If we still make the index negative, it will be considered zero and the index cannot be a decimal, if it is a decimal it will be converted to an integer smaller than it is.
Let’s take a look at the example
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var string = "sghxdysgcghd"; a = string.substring(-1) b = string.substring(2.5) c = string.substring(2.9) document.write(a + "<br>"); document.write(b + "<br>"); document.write(c + "<br>"); </script> </body> </html>
The display effect on the browser is as follows
This article is here It’s all over here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !
The above is the detailed content of How to use substring method. For more information, please follow other related articles on the PHP Chinese website!