保埃科技网
您的当前位置:首页对JavaScript字符串方法的总结

对JavaScript字符串方法的总结

来源:保埃科技网


本篇文章讲述了JavaScript字符串方法,大家对JavaScript字符串方法不了解的话或者对JavaScript字符串方法感兴趣的话那么我们就一起来看看本篇文章吧, 好了废话少说进入正题吧!

测试数组str=”China”;
下面各个方法对str的测试互不影响。

截取字符串

substr(start,length)
start:(必选)要截取子串的起始位置,负值:-1 指字符串中最后一个字符,-2 指倒数第二个字符…
length:(可选)要截取子串的长度,省略表示截取到末尾
返回新字符串。

console.log(str); //China

console.log(str.substr(1)); //hina
console.log(str.substr(-1)); //a
console.log(str.substr(1,2)); //hi
console.log(str.substr(-3,1)); //i

slice(start,end【不包括该位置元素】)
start:(必选)要截取子串的起始位置,负值:-1 指字符串中最后一个字符,-2 指倒数第二个字符…
end:(可选)要截取子串的结束位置(不包括该位置),省略表示截取到末尾
返回新字符串。

console.log(str); //China

console.log(str.slice(1)); //hina
console.log(str.slice(1,2)); //h
console.log(str.slice(1,-1)); //hin

console.log(str.slice(-1)); //a
console.log(str.slice(-3,-1)); //in
console.log(str.slice(-3,3)); //i

substring(start,end)整数截取
start:(必选)要截取子串的起始位置,负值:-1 指字符串中最后一个字符,-2 指倒数第二个字符…
end:(可选)要截取子串的结束位置(不包括该位置),省略表示截取到末尾
返回新字符串。
注意:substring和slice不同的是,substring不接受负的参数(所谓不接受:可以传负参数,结果不正确)

console.log(str) //China 

console.log(str.substring(1)) //hina 
console.log(str.substring(1,3)) //hi

搜索字符串

charAt(index)
index:(必选)搜索的字符串下标
返回index位置的字符

//w3c给的标准是必选,但是浏览器是支持的,无参相当于传入0
console.log(str.charAt()); //C,无参,默认0
console.log(str.charAt(1)); //h
console.log(str.charAt(9)); //'',不在范围,空

charCodeAt(index)
index:(必选)搜索的字符串下标
指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数

console.log(str.charCodeAt(1)); //104(h)
console.log(str.charCodeAt()); //67(C),无参,默认0
console.log(str.charCodeAt(9)); //Nan(''),不在范围,空

indexOf(searchValue,fromIndex)
searchValue:(必选)搜索的子串
fromIndex:(可选)搜索的起始位置,省略表示位置0
返回searchValue子串在字符串(str)中首次出现的位置,无则返回-1

console.log(str.indexOf('c')); //-1,区分大小写
console.log(str.indexOf('h')); //1
console.log(str.indexOf('h', 2)); //-1

lastIndexOf(searchValue,fromIndex)
该方法从后面搜索字符串,indexOf()方法则从前面,其余两者一样。

var s = 'China,china';
console.log(s.lastIndexOf('A')); //-1
console.log(s.lastIndexOf('i')); //8
console.log(str.lastIndexOf('asi')); //-1
console.log(s.lastIndexOf('c', 2)); //-1

search(str/regexp)
str/regexp:(必选)要搜索的子串或要匹配的正则表达式
返回子串第一次出现的位置,或正则表达式的第一个匹配位置(不支持全局g)。无则返-1。

console.log(str.search(/ch/)); //-1
console.log(str.search(/Ch/)); //0
console.log(str.search(/ch/i)); //0,/i大小写忽略

console.log(str.search('a')); //5
str.concat(str1,str2…)

str为连接的第一个字符串,str1为第二个字符串,str2为第三个,一次类推。
返回新字符串

var aa = 'aa';
var bb = 'bb';
var cc = 'cc';

console.log(cc.concat(aa, bb)); //ccaabb 
console.log(cc); //cc
显示全文