js中的replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串
例如:
用字符替换,我们将使用 "W3School" 替换字符串中的 "Microsoft"
var str="Visit Microsoft!"
documentwrite(strreplace(/Microsoft/, "W3School"))
输出:Visit W3School!
用正则替换,我们将前后空格去掉
name = ' 12 33 ';
name =name replace(/(^\s)|(\s$)/g,'');
输出:12 33
也可以借鉴>js中的特殊字符,加上转义符\ 。
例如:
var txt="We are the so-called "Vikings" from the north" documentwrite(txt) 错误
var txt="We are the so-called \"Vikings\" from the north" documentwrite(txt) 正确
1、一般常用的,替换字符串中的""
var result = "abcdefg"replace("","");//abcdefg
consolelog(result);
2、跟1比较,发现只能替换一次,一般建议用循环进行多次替换
var result2 = "abcdefghijklmn"replace("","");//abcdefghijklmn
consolelog(result2);
3、使用正则表达式进行替换
var reg = /\/g;//创建正则,表示替换全局替换""
var result3 = "abcdefghijklmn"replace(/\/g,"");//abcdefghijklmn
consolelog(result3);
补充:
正则格式:/pattern/标识符,如/\/g,
因为是特殊字符,需要\进行转义,然后g标识全局查找,如果不写这个,就不会进行全局替换
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)