Access the substring of a string in JavaScript

  • 2020-07-21 06:52:00
  • OfStack

Using the substring() or slice() methods (NN4+, IE4+), the details of their usage are described below.


The prototype of substring() is:


string.substring(from, to)


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


What if the parameter from is accidentally larger than the parameter to? JavaScript automatically mediates the start and end of the substring, that is, substring() always starts with the smaller of the two arguments and ends with the larger one. Note, however, that it contains the character at the beginning but not the character at the end.


   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() The prototype is:  string.slice(start, end)



The parameter start refers to the starting position of the substring. If it is negative, it can be interpreted as starting from the last digit. For example, -3 means starting from the last digit. The parameter end represents the end position. Like start1, it can also be negative, meaning up to the penultimate end. The argument to slice() can be negative, so it is more flexible than substring(), but less forgiving; if start is larger than end, it returns an empty string (omitted from the example).


Another method is substr(), whose prototype is:


string.substr(start, length)


You can see from the prototype what its parameters mean, with start representing the starting position and length the length of the substring. The JavaScript standard does not advocate this approach.


Related articles: