var str="hello world!"; console.log(str.search("o"));//4找到第一个字符串o就返回o的索引 console.log(str.search("a"));//-1找不到字符串a返回-1
var str="hello world!"; console.log(str.substring(2,7));//从索引为2到6不包含6,空格也算 console.log(str.substring(2));//索引从2到最后
var str="hello world!"; console.log(str.charAt(4));//o返回索引为4的元素
var str="hello world! my name is amy"; console.log(str.split(" "));//按照空格切字符串["hello", "world!", "my", "name", "is", "amy"]
var str="45 abc 12 def89 */*-86"; var arr=[]; var tmp=""; for(var i=0; i<str.length; i++){ if(str.charAt(i)>"0" && str.charAt(i)<="9"){ tmp+=str.charAt(i); }else{ if(tmp){ arr.push(tmp); tmp=""; } } } if(tmp){ arr.push(tmp); tmp=""; } console.log(arr);//["45", "12", "89", "86"]
var str="45 abc 12 def89 */*-86"; console.log(str.match(/\d+/g));//["45", "12", "89", "86"]
replace常常跟正则配合使用。正则表达式
var str="hello world!"; console.log(str.replace("o","A"));//hellA world!把o替换成A,只能替换第一个 var re=/o/g; console.log(str.replace(re,"A"));//hellA wArld!利用正则中的g就能够替换掉全部的o