You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
vars="hello ECMAScript5.1 and ECMAScript2015";console.log(s.slice(6,19));//ECMAScript5.1console.log(s.slice(6,-4));//ECMAScript5.1 and ECMAScriptconsole.log(s.slice(-14,-4));//ECMAScriptconsole.log(s.slice(0,-14));//hello ECMAScript5.1 andconsole.log(s.slice(-14));//ECMAScript2015
slice与substring同为截取字符串的一部分,也同样有两个参数(包含起始位置不包含结束位置)。下面来描述一下slice和substring的两个参数的使用方法如下:
1、slice
两个参数分别表示截取字符串的起始位置和结束位置,如果大于0,则从前面计数,如果小于0,则从后面计数,如果省略第二个参数,则会截取到字符串的尾部,参照下面的示例更容易理解:
2、substring
两个参数分别表示字符串的起始位置和结束位置,所不同的是substring中如果结束位置在起始位置之前,则会自动将其调换后截取,当参数小于0 时按0处理,如果省略第二个参数,则会截取到字符串的尾部,参照下面的示例更容易理解:
区别:
扩展:substr
(ECMAscript 没有对该方法进行标准化,因此反对使用它。)
substr()方法可在字符串中抽取从start下标开始的指定数目的字符串
语法:str.substr(start,length)截取str从start开始的length个字符(包含起始位置)
说明:start参数可以是任意整数,如果是负数,则从str的尾部开始算起,例如-1就是str的最后一个字符。
length是可选的,如果没有,则表示截取从str开始的位置到字符串的尾部
例子:
总结:String 对象的方法 slice()、substring() 和 substr() (不建议使用)都可返回字符串的指定部分。slice() 比 substring() 要灵活一些,因为它允许使用负数作为参数。slice() 与 substr() 有所不同,因为它用两个字符的位置来指定子串,而 substr() 则用字符位置和长度来指定子串。
The text was updated successfully, but these errors were encountered: