js字符串操作
字符串切割和提取
1、slice()函数:
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()函数:
var mystr="hello world!"; var sliceStr1=mystr.substring(3); //lo world! var sliceStr2=mystr.substring(3,7); //lo w
3、substr()函数:
var mystr="hello world!"; var sliceStr1=mystr.substr(3); //lo world! var sliceStr2=mystr.substr(3,7); //lo wo
字符串去空格
var mystr=" hello world "; var trimStr=mystr.trim(); //hello world
字符串替换
var mystr="wozaijinxingzifuchuantihuancaozuo,zifuchuantihuano"; var replaceStr=mystr.replace("zifuchuan"," "); //wozaijinxing tihuancaozuo,zifuchuantihuano var replaceStr=mystr.replace(/zifuchuan/," "); //wozaijinxing tihuancaozuo,zifuchuantihuano var replaceStr=mystr.replace(/zifuchuan/g," "); //wozaijinxing tihuancaozuo, tihuano
字符串分割
将字符串进行拆分返回一个新的数组
var mystr="qingchenghuwoguoxiansheng,woaishenghuo,woaiziji"; var arr1=mystr.split(","); //["qingchenghuwoguoxiansheng","woaishenghuo","woaiziji"]; var arr2=mystr.split(""); //["q","i","n","g","c","h","e","n","g","h","u","w","o","g","u","o","x","i","a","n","s","h","e","n","g",",","w","o","a","i","s","h","e","n","g","h","u","o",",","w","o","a","i","z","i","j","i"];
split()的第二个参数,表示返回的字符串数组的最大长度
var mystr="qingchenghuwoguoxiansheng,woaishenghuo,woaiziji"; var arr1=mystr.split(",",2); //["qingchenghuwoguoxiansheng","woaishenghuo"]; var arr2=mystr.split("",8); //["q","i","n","g","c","h","e","n"];