js replace(a,b)替换字符串中所有指定字符的方法
var str = 'aaabbbccc'; var str1 = str.replace('a', 'e'); alert(str1);
打印结果: eaabbbccc
var str2 = str.replace(/a/g, 'o');//g是重点,如果替换的为‘/’,需要转义,吧/a/g替换为'/\//g' alert(str2);
打印结果: eeebbbccc
完整代码演示
<!doctype html> <html> <head> <meta charset="utf-8"> <title>js替换指定字符串</title> </head> <body> <script type="text/javascript"> var astr = 'aaabbbccc'; var astr1 = astr.replace('a', 'e'); alert("aaabbbccc替换结果为:"+astr1); var str = 'aaabbbccc'; var str1 = str.replace(/a/g, 'e'); alert("aaabbbccc替换结果为:"+str1); </script> </body> </html>