您的当前位置:首页>全部文章>文章详情

javascript对字符串的切割截取方法集合

发表于:2021-08-30 22:41:37浏览:1363次TAG: #javascript #截取字符串

js切割字符串主要有下面几种,这里主要记录一下。

1、slice(start, end) 方法

start:起始索引(开始位置)

end:终止索引(结束位置)

如果某个参数为负,则从字符串的结尾开始计数

如果省略第二个参数,则该方法将裁剪字符串的剩余部分

var str = "GouguCms,GouguBlog,GouguEdu";
 
var res1 = str.slice(6,12);
var res2 = str.slice(-12,-6);
var res3 = str.slice(6);
var res4 = str.slice(-12);
//结果
console.log(res1);//ms,Gou
console.log(res2);//log,Go
console.log(res3);//ms,GouguBlog,GouguEdu
console.log(res4);//log,GouguEdu

2. substring(start, end)方法

substring() 类似于 slice(),不同的是substring无法接受负的索引。


3.substr(start, length)方法

substr() 也是类似于 slice(),不同之处在于第二个参数规定被提取部分的长度。

var str = "GouguCms,GouguBlog,GouguEdu";
var res = str.substr(6,8);
//结果
console.log(res);//ms,Gougu

4.split() 方法用于把一个字符串分割成字符串数组

"2:3:4:5".split(":")	//将返回["2", "3", "4", "5"]
"|a|b|c".split("|")	//将返回["", "a", "b", "c"]

5.charAt(position)

var str = "HELLO WORLD";
str.charAt(0);            // 返回 H