这个问题在这里已有答案:
我有一个包含多个逗号的字符串,字符串替换方法只会更改第一个:
var mystring = "this,is,a,test" mystring.replace(",","newchar", -1)
Result : "thisnewcharis,a,test"
"thisnewcharis,a,test"
文档指出默认值替换all,并且“-1”也表示替换all,但是不成功 . 有什么想法吗?
String.prototype.replace()函数的第三个参数从未被定义为标准,因此大多数浏览器根本不实现它 .
var myStr = 'this,is,a,test'; var newStr = myStr.replace(/,/g, '-'); console.log( newStr ); // "this-is-a-test"
重要的是要注意,正则表达式使用special characters that need to be escaped . 例如,如果需要转义点( . )字符,则应使用 /\./ literal,如在正则表达式语法中,点匹配任何单个字符(行终止符除外) .
.
/\./
var myStr = 'this.is.a.test'; var newStr = myStr.replace(/\./g, '-'); console.log( newStr ); // "this-is-a-test"
如果需要将变量作为替换字符串传递,而不是使用正则表达式文字,则可以创建 RegExp object和pass a string as the first argument of the constructor . 正常的字符串转义规则(当包含在字符串中时带有 \ 的特殊字符之前)将是必要的 .
RegExp
\
var myStr = 'this.is.a.test'; var reStr = '\\.'; var newStr = myStr.replace(new RegExp(reStr, 'g'), '-'); console.log( newStr ); // "this-is-a-test"
纯娱乐:
var mystring = "this,is,a,test" var newchar = '|' mystring = mystring.split(',').join(newchar);
var mystring = "this,is,a,test" mystring.replace(/,/g, "newchar");
使用全局( g )标志
g
Simple DEMO
3 回答
String.prototype.replace()函数的第三个参数从未被定义为标准,因此大多数浏览器根本不实现它 .
最好的方法是使用带有g(全局)标志的正则表达式 .
还有问题吗?
重要的是要注意,正则表达式使用special characters that need to be escaped . 例如,如果需要转义点(
.
)字符,则应使用/\./
literal,如在正则表达式语法中,点匹配任何单个字符(行终止符除外) .如果需要将变量作为替换字符串传递,而不是使用正则表达式文字,则可以创建
RegExp
object和pass a string as the first argument of the constructor . 正常的字符串转义规则(当包含在字符串中时带有\
的特殊字符之前)将是必要的 .纯娱乐:
使用全局(
g
)标志Simple DEMO