JavaScript - 替换字符串中的所有逗号 [英] JavaScript - Replace all commas in a string
问题描述
我有一个包含多个逗号的字符串,字符串替换方法只会更改第一个:
I have a string with multiple commas, and the string replace method will only change the first one:
var mystring = "this,is,a,test"
mystring.replace(",","newchar", -1)
结果:thisnewcharis,a,test
文档指示默认值替换all,并且-1也表示替换all,但是不成功。有什么想法?
The documentation indicates that the default replaces all, and that "-1" also indicates to replace all, but it is unsuccessful. Any thoughts?
推荐答案
String.prototype.replace()
函数从未被定义为标准,所以大多数浏览器都没有实现它。
The third parameter of String.prototype.replace()
function was never defined as a standard, so most browsers simply do not implement it.
var myStr = 'this,is,a,test';
var newStr = myStr.replace(/,/g, '-');
console.log( newStr ); // "this-is-a-test"
重要的是要注意,正则表达式使用需要转义的特殊字符。例如,如果你需要转义一个点(。
)字符,你应该使用 / \ ./
literal,正如在regex语法中一个点匹配任何单个字符(行终止符除外)。
It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.
) character, you should use /\./
literal, as in the regex syntax a dot matches any single character (except line terminators).
var myStr = 'this.is.a.test';
var newStr = myStr.replace(/\./g, '-');
console.log( newStr ); // "this-is-a-test"
如果你需要将变量作为替换字符串传递,而不是使用正则表达式文字,您可以创建 RegExp
对象和传递一个字符串作为构造函数的第一个参数。正常的字符串转义规则(包含在字符串中的 \
之前的特殊字符)将是必要的。
If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp
object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \
when included in a string) will be necessary.
var myStr = 'this.is.a.test';
var reStr = '\\.';
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');
console.log( newStr ); // "this-is-a-test"
这篇关于JavaScript - 替换字符串中的所有逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!