字符串方法
tip这个是我自己总结的,可能不全,可能有错(望指证),有兴趣的朋友可以去官网查看这些方法。
- length
- 返回字符串的长度
var str='jcidjfdsijfs';
console.log(str.length);//12
- indexOf(searchVlue[,fromIndex])
- 返回字符串在指定文本中第一次出现的索引,从fromIndex开始搜索,若未找到,则返回-1
var str='hello world';
console.log(str.indexOf("lo"));//3
console.log(str.indexOf("lo",3));//-1
- lastIndexOf(searchVlue[,fromIndex])
- 返回字符串在指定文本中最后一次出现的索引,若未找到,则返回-1
var str='hello world';
console.log(str.lastIndexOf("l"));//9
- search()
- 执行正则表达式和String对象之间的一个搜索匹配,若匹配成功,则返回正则表达式在字符串中首次出现的匹配项的索引,否则返回-1
var str="heLlo WoRld";
var reg=/[A-Z]/g;
console.log(str.search('lo'));//3
- 截取字符串的方法
- slice(start,end)
提取字符串的一部分,并返回一个新的字符串(从原来的字符串中提取出来的新字符串),且不会改变原来的字符串
var str='hello world';
console.log(str.slice(2,5));//llo
console.log(str);//hello world
- substring(start,end)
方法返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集
var str='hello world';
console.log(str.substring(2,5));//llo
console.log(str);//hello world
- substr(start,length)
返回一个字符串中从指定位置开始到指定字符数的字符
var str='hello world';
console.log(str.substr(2,5));//llo w
console.log(str);//hello world
- replace()
- 用另一个值来替换在字符串中的指定值,该方法不会改变原字符串
var str='hello world';
console.log(str.replace("hello","HELLO"));//HELLO world
console.log(str);//hello world
- 字符串大小写转换
- toUpperCase()将字符串转换为大写
- toLowerCase()将字符串转换为小写
var str='HELLO world';
console.log(str.toUpperCase());//HELLO WORLD
console.log(str);//HELLO world
console.log(str.toLowerCase());//hello world
console.log(str);//HELLO world
- concat()
- 连接两个或者多个字符串
var str1='hello';
var str2='world';
console.log(str1.concat(str2));//helloworld
- trim()
- 去除字符串两端的空白字符
var str=' hello world '
console.log(str.trim());//hello world
- charAt()
- 返回字符串中指定下标的字符串
var str='hello world';
console.log(str.charAt(6));//w
console.log(str);//hello world
- charCodeAt()
- 返回字符串中指定索引的字符的unicode编码
var str='hello world';
console.log(str.charCodeAt(6));//119
- split()
- 可以将字符串分割成为一个数组
var str='hello world';
console.log(str.split(''));//['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
console.log(str.split('l'));//['he', '', 'o wor', 'd']