一.字符串切割与提取
1.slice(start,end);两个参数可正可负,负值代表从右截取
var mystr="hello world!";
var sliceStr1=mystr.slice(-3); //ld!
var sliceStr2=mystr.slice(-3,-1); //ld
var sliceStr3=mystr.slice(3);//lo world!
var sliceStr4=mystr.slice(3,7); //lo w
2.substring(start,end);两个参数都为正数
var mystr="hello world!"
var sliceStr1=mystr.substring(3); //lo world!
var sliceStr2=mystr.substring(3,7); //lo w
3.substr(start,length);start参数可正可负,负数代表从右截取,length为截取长度
var mystrEmpty = ' hello world!'
console.log(mystrEmpty.substr(4));//lo world!
console.log(mystrEmpty.substr(5,3));//o w
二.其它方法
4.charAt(index);返回子字符串,index为字符串下标
var mystr="hello world!";
console.log(mystr.charAt(4));//o
5.charCodeAt(index);返回子字符串的unicode编码
var mystr="hello world!";
console.log(mystr.charCodeAt(4));//111
6.fromCharCode(num1,num2);静态方法,根据unicode编码返回字符串
console.log(String.fromCharCode(111))//o
7.indexOf(searchString,startIndex);返回子字符串第一次出现的位置,从startIndex开始查找,找不到时返回-1
var mystr="hello world!";
console.log(mystr.indexOf("o",5));//7
console.log(mystr.indexOf("o"));//7
console.log(mystr.indexOf("x"));//-1
8.lastIndexOf(searchString,startIndex);从右往左找子字符串,找不到时返回-1
var mystr="hello world!";
console.log(mystr.lastIndexOf("x"));//-1
console.log(mystr.lastIndexOf("d"));//10
console.log(mystr.lastIndexOf("d",2));//-1
9.split(separator,limit);字符串分割成数组,参数1指定字符串或正则,参数2指定数组的最大长度
var mystr="hello world!";
console.log(mystr.split());//["hello world!"] 整个字符串放到数组中
console.log(mystr.split(''));//["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
console.log(mystr.split('l'));//["he", "", "o wor", "d!"]
console.log(mystr.split('l',2));// ["he", ""]
10.match(pattern); 正则匹配,字符串或者正则表达式
var mystr="hello world!";
console.log(mystr.match(/l/));//["l", index: 2, input: "hello world!", groups: undefined]
console.log(mystr.match(/d/));//["d", index: 10, input: "hello world!", groups: undefined]
console.log(mystr.match(/x/));//null
console.log(mystr.match(/l/g));//["l", "l", "l"]
console.log(mystr.match(/d/g));//["d"]
console.log(mystr.match(/x/g));//null
console.log(mystr.match("l"));//["l", index: 2, input: "hello world!", groups: undefined]
11.search(pattern);返回值是匹配项的索引,如果没有找到匹配的子字符串,则返回-1
var mystr="hello world!";
console.log(mystr.search(/l/));//2
console.log(mystr.search(/l/g));//2
console.log(mystr.search("l"));//2
console.log(mystr.search("x"));//-1
12.replace(rgExp/substr,replaceText),返回替换后的字符串
var mystr="hello world!";
console.log(mystr.replace("l","5"));//he5lo world! 只替换第一个l
console.log(mystr.replace(/l/g,"5"));//he55o wor5d! 替换所有l
13.trim(); 删除字符串头和尾部的空格
var mystrEmpty = ' hello world!'
console.log(mystrEmpty.trim());//hello world! 删除字符串头和尾部的空格
扩展:去除字符串内所有空格
function(str) {
return str.replace(/\s+/g, "");
}
14.toLowerCase(),toUpperCase();大小写
var mystrEmpty = ' hello world!'
console.log(mystrEmpty.toLowerCase());//" hello world!"
console.log(mystrEmpty.toUpperCase());//" HELLO WORLD!"