Home > Web Front-end > JS Tutorial > Accessing substrings of strings in JavaScript_Basics

Accessing substrings of strings in JavaScript_Basics

WBOY
Release: 2016-05-16 15:51:09
Original
1073 people have browsed it

Use substring() or slice() method (NN4, IE4), their specific usage is explained below.


The prototype of substring() is:

string.substring(from, to)
Copy after login


The first parameter from specifies the starting position of the substring in the original string (based on 0 index); the second parameter to is optional, and it specifies the ending position of the substring in the original string (based on 0). index), in general, it should be larger than from. If it is omitted, the substring will go to the end of the original string.


What happens if the parameter from accidentally becomes larger than the parameter to? JavaScript will automatically adjust the starting and ending positions of the substring, that is, substring() always starts from the smaller of the two parameters and ends with the larger one. Note, however, that it includes the character at the starting position, but not the character at the ending position.

   var fullString = "Every dog has his day.";


   var section = fullString.substring(0, 4); // section is "Ever".


   section = fullString.substring(4, 0);   // section is also "Ever".


   section = fullString.substring(1, 1);   // section is an empty string.


   section = fullString.substring(-2, 4); // section is "Ever", same as fullString.substring(0, 4);  slice()的原型为: string.slice(start, end)

Copy after login



The parameter start represents the starting position of the substring. If it is a negative number, it can be understood as the starting position from the last to last. For example, -3 means starting from the third from the last. The parameter end represents the ending position. Like start, it can also be a negative number. , its meaning also indicates the end of the penultimate number. The parameters of slice() can be negative, so it is more flexible than substring(), but less tolerant. If start is larger than end, it will return an empty string (example omitted).


There is another method is substr(), its prototype is:

string.substr(start, length)
Copy after login


From the prototype, we can see the meaning of its parameters. start represents the starting position, and length represents the length of the substring. The JavaScript standard discourages the use of this method.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template