1.字符串分割
1 var myStr = "I,Love,You,Do,you,love,me"; 2 var substrArray = myStr .split(","); // ["I", "Love", "You", "Do", "you", "love", "me"]; 3 var arrayLimited = myStr .split(",", 3); // ["I", "Love", "You"];
2.查询子字符串
1 第一个函数:indexOf(),它从字符串的开头开始查找,找到返回对应坐标,找不到返回-1。如下: 2 5 var myStr = "I,Love,you,Do,you,love,me"; 6 var index = myStr.indexOf("you"); // 7 ,基于0开始,找不到返回-1 7 第二个函数:lastIndexOf(),它从字符串的末尾开始查找,找到返回对应坐标,找不到返回-1。如下: 8 9 var myStr = "I,Love,you,Do,you,love,me"; 12 var index = myStr.lastIndexOf("you"); // 14
3.字符串替换
var myStr = "I,love,you,Do,you,love,me"; var replacedStr = myStr.replace("love","hate");//"I,hate,you,Do,you,love,me" //正则替换 var myStr = "I,love,you,Do,you,love,me"; var replacedStr = myStr.replace(/love/g,"hate");//"I,hate,you,Do,you,hate,me"
4.字符串切割和提取
1 var myStr = "I,love,you,Do,you,love,me"; 2 var subStr = myStr.slice(1,5);//",lov"
5.字符串匹配(exec相反)
1 var myStr = "I,love,you,Do,you,love,me"; 2 var pattern = /love/; 3 var result = myStr.match(pattern);//["love"]
//var
result = pattern .exec(myStr);
//["love"] 或者是
4 console.log(result .index);//2 5 console.log(result.input );//I,love,you,Do,you,love,me
也可以用search
1 var myStr = "I,love,you,Do,you,love,me"; 2 var pattern = /love/; 3 var result = myStr.search(pattern);//2.