正则
var str = "abcdefsafsf"; var subStr = "f"; var reg = new RegExp(subStr,"gi");//等价于/f/gi str = str.replace( reg, subStr+','); console.log(reg); console.log(str); //结果abcdef,saf,sf,
二、替换所有指定的字符
var str = "abcdefsafsf"; var repstr = "c"; console.log(replaceFun(str, repstr, "<span>" + repstr + "</span>")); function replaceFun(str, repstr, newrepstr) { var reg = new RegExp(repstr,"gi"); return str.replace( reg, newrepstr); }
三、转换成数组
var str = "fabcdefsafsffffs"; var subStr = "f"; console.log(regStrArr(str,subStr)); function regStrArr(str,subStr){ var reg = new RegExp(subStr,"gi"); str = str.replace( reg, ','+subStr+','); var strArr = []; (str.split(",")).forEach(function(i,j){ if(i!=""){ strArr.push(i); } }); console.log(strArr); return strArr; }