您的位置:首页 > Web前端 > JavaScript

js String对象

2015-07-13 21:51 686 查看
String对象方法介绍

1,连接字符串“+” concat()

var a = "abc".concat("efg");
console.log(a);// abcefg
concat方法连接字符串,原字符串不变,返回新字符串

2,取子串

substring(),substr(),slice()

"hello world".substring(3,4); // l
"hello world".substring(4,3); // l

"hello world".substr(3,4);     // lo w
"hello world".substr(4,3);    //  o w

"hello world".slice(3,4); // l
"hello world".slice(4,3); // ""
三个方法的第一个参数都是字符串的起始位置,第二个参数含义不同,substr()方法表示长度。

substring()和slice()第二个参数表示结束位置。如果结束位置小于起始位置,二者有区别,substring方法自动调换参数位置然后返回slice方法不会调换位置而是返回空字符串。

如果都只取一个参数,则表示从起始位置到字符串结尾。

"hello world".substring(3,-3); // hel
"hello world".substring(-3); // hello world

"hello world".substr(3,-3);     // ""
"hello world".substr(-3);    //  rld

"hello world".slice(3,-3); // lo wo
"hello world".slice(-3); // rld
如果参数为负数 又各有不同

substring方法将负数转化为0 所以substring(3.-3)转成substring(3.0),二参小于一参,互换位置,substring(0,3)

substr方法第一个参数为负数,则从尾部开始(最后一位为-1);第二个参数为负数,则转化为0,substr(3.-3)转化成substr(3.0) 所以返回空串

slice方法则表示从尾部计算

trim()方法去除两端的空格

indexOf() lastIndexOf(),分别表示从头和尾部找出某字符的位置

localeCompare()方法比较量字符串的大小(unicode)第一个大于第二个返回1,小于返回-1,等于返回0.如果俩字符串首字母相同比较第二个,第二个相同比较第三个。。。

字符串的搜索与替换方法

match方法 ,返回匹配字符的数组,数组包括匹配字符,及其位置和原始字符

var matches = "cat, bat, sat, fat".match("t");
console.log(matches); // ["t", index: 2, input: "cat, bat, sat, fat"]


search()方法

跟match用法相同,返回匹配字符的开始位置,即上面的index的值

var matches = "cat, bat, sat, fat".search("t");
console.log(matches); //2
replace()替换

只替换第一个匹配的元素,除非用正则

console.log("aaa".replace("a", "b"));//baa
split()方法分割字符串返回数组

console.log("aaa".split(""));//["a","a","a"]
console.log("aaa".split("", 2)); <span style="font-family: Arial, Helvetica, sans-serif;">["a","a"]</span>
//可以接受第二个参数,表示返回数组的最长度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: