Home > Web Front-end > JS Tutorial > body text

What are the differences between substring, slice and substr in js?

coldplay.xixi
Release: 2020-06-30 14:51:04
Original
3494 people have browsed it

The differences between substring, slice and substr in js are: 1. slice and substring receive the starting position and end position, while substr receives the starting position and the length of the string to be returned; 2. , slice adds the length of the string to the corresponding negative number, and the result is used as a parameter.

What are the differences between substring, slice and substr in js?

The differences between substring, slice and substr in js are:

  • slice() method returns selected elements from an existing array.

  • string.slice(start, end)Extract a string

  • string.substring(start , end)Extract a string, end does not support negative numbers

  • string.substr(start, len)Extract a string with a length of len

1. slice and substring receive the starting position and end position (excluding the end position), while substr receives the starting position and the length of the string to be returned. Look directly at the following example:

   var test = 'hello world';
   alert(test.slice(4,7));             //o w
   alert(test.substring(4,7));         //o w
   alert(test.substr(4,7));            //o world
Copy after login

2. Substring uses the smaller of the two parameters as the starting position and the larger parameter as the ending position. For example:

     alert(test.substring(7,4)); //o w
Copy after login

3. When the received parameter is a negative number, slice will add the length of its string to the corresponding negative number, and the result will be used as the parameter; substr will only add the first parameter to the string. The result of adding the lengths is used as the first parameter; substring simply converts all negative parameters directly to 0. The test code is as follows:

var test = 'hello world';
alert(test.slice(-3));         //rld
alert(test.substring(-3));     //hello world
alert(test.substr(-3));        //rld
alert(test.slice(3,-4));       //lo w
alert(test.substring(3,-4));   //hel
alert(test.substr(3,-4));      //空字符串
Copy after login

Related learning recommendations: javascript video tutorial

The above is the detailed content of What are the differences between substring, slice and substr in js?. For more information, please follow other related articles on the PHP Chinese website!

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