js--字符串经常使用方法

1.charAt:返回字符串的给定位置的字符串code

var arr = 'abcdefg';
console.log(arr.length);//7
console.log(arr.charAt(1));//b
console.log(arr[1]);//b

2.concat:链接2个字符串。原来的不变字符串

var b = arr.concat("abc");
console.log(b);// "abcdefgcde"

3.substring,substr,slice均可省略第二个参数,表示持续到字符串结束。string

substring(x,y)返回从x到y(不包括y)it

var s = arr.substring(1,3);
console.log(s);// "bc"

substr(x,y)返回从x开始的长度为y的字符串console

var s = arr.substr(1,3);
console.log(s);// "bcd"

slice(x,y)返回从x到y(不包括y)位置颠倒时,结果为空字符串ast

var s = arr.slice(1,3);
console.log(s);// bc
var s = arr.slice(3,1);
console.log(s);//  ""

4.trim 去掉两端的空格,不影响以前的字符串gc

var arr = '  abcdefg     ';
var a = arr.trim();
console.log(a);//abcdefg

5.toLowerCase,toUpperCase 转为大小写,原来的不变im

var="abcdefg";
var b = arr.toUpperCase();
console.log(b);//"ABCDEFG"
var c = c.toLowerCase();
console.log(c);//"abcdefg"

6.indexOf,lastIndexOf 肯定一个字符串在另外一个字符串中的第一次出现的位置,一个从头部开始,一个从尾部开始co

var arr = 'abccba';
var b = arr.indexOf('b');
console.log(b);// 1
var c = arr.lastIndexOf('c');
console.log(c);// 3

他们还能够接受第二个参数,对于indexOf,表示从该位置向后匹配,对于lastIndexOf,表示从该位置起向前匹配字符

7.split 切割字符串

var arr = 'a b c c b a';
var b = arr.split(' ');
console.log(b);// ["a", "b", "c", "c", "b", "a"]
相关文章
相关标签/搜索