Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slice、substring 和 substr 的区别 #95

Open
vincentzyc opened this issue Jul 29, 2022 · 0 comments
Open

slice、substring 和 substr 的区别 #95

vincentzyc opened this issue Jul 29, 2022 · 0 comments

Comments

@vincentzyc
Copy link
Owner

slice与substring同为截取字符串的一部分,也同样有两个参数(包含起始位置不包含结束位置)。下面来描述一下slice和substring的两个参数的使用方法如下:

1、slice

两个参数分别表示截取字符串的起始位置和结束位置,如果大于0,则从前面计数,如果小于0,则从后面计数,如果省略第二个参数,则会截取到字符串的尾部,参照下面的示例更容易理解:

    var s = "hello ECMAScript5.1 and ECMAScript2015";
    console.log(s.slice(6,19)); //ECMAScript5.1
    console.log(s.slice(6,-4)); //ECMAScript5.1 and ECMAScript
    console.log(s.slice(-14,-4)); //ECMAScript
    console.log(s.slice(0,-14)); //hello ECMAScript5.1 and
    console.log(s.slice(-14)); //ECMAScript2015

2、substring

两个参数分别表示字符串的起始位置和结束位置,所不同的是substring中如果结束位置在起始位置之前,则会自动将其调换后截取,当参数小于0 时按0处理,如果省略第二个参数,则会截取到字符串的尾部,参照下面的示例更容易理解:

    var w = "www.excelib.com";
    console.log(w.substring(4,11)); //excelib
    console.log(w.substring(11,4)); //excelib
    console.log(w.substring(3,-4)); //www
    console.log(w.substring(3,0)); //www
    console.log(w.substring(4)); //excelib.com

区别:

1、substring:两个参数会比较大小来判断哪一个是起始位参数哪一个是结束位置参数,通俗的讲就是小的一个数会作为起始 位置参数,大的一个数会作为结束位置参数;
slice:则不会有这样的规则,只遵循大于0,从前面计数,小于0,从后面计数的原则。
2、substring:除了两个参数会比较大小调换位置外,还满足小于0时按0处理的规则;
slice:则是根据大于0和小于0来判断计数的前后顺序

扩展:substr

(ECMAscript 没有对该方法进行标准化,因此反对使用它。)
substr()方法可在字符串中抽取从start下标开始的指定数目的字符串
语法:str.substr(start,length)截取str从start开始的length个字符(包含起始位置)
说明:start参数可以是任意整数,如果是负数,则从str的尾部开始算起,例如-1就是str的最后一个字符。
length是可选的,如果没有,则表示截取从str开始的位置到字符串的尾部

例子:

   var str = 'abcde leodonna'
   console.log(str.substr(8))//odonna
   console.log(str.substr(-4))//onna
   console.log(str.substr(4,4))//e le
   console.log(str.substr(-3,6))//nna

总结:String 对象的方法 slice()、substring() 和 substr() (不建议使用)都可返回字符串的指定部分。slice() 比 substring() 要灵活一些,因为它允许使用负数作为参数。slice() 与 substr() 有所不同,因为它用两个字符的位置来指定子串,而 substr() 则用字符位置和长度来指定子串。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant