Home  >  Article  >  Web Front-end  >  js字符串截取函数substr substring slice使用对比_javascript技巧

js字符串截取函数substr substring slice使用对比_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:12:061426browse

常用三个的字符串截取函数:substr substring slice,调用方式如下

复制代码 代码如下:

stringObject.slice(start,end)
stringObject.substr(start,length)
stringObject.substring(start,end)

最明显的是substr,第二个参数是length,是截取长度,其他两个函数的第二个参数都是末尾字符的下标(这里并不包括该下标的字符,只截取到该字符的前一个字符)

slice跟substring比,slice下标可以是负数,比如-1表示最后一个字符,而substring不能。substring如果 start 比end 大,那么在提取子串之前会先交换这两个参数,而slice不会,slice会返回空字符串

例子:
复制代码 代码如下:

var str="Helloworld"
console.log(str.substr(0, 2))
console.log(str.substring(2, 0))
console.log(str.substring(0, 2))
console.log(str.slice(0, -1))
console.log(str.slice(-1, 0))

输出:

He
He
He
Helloworl
(空字符串)
Statement:
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