JavaScript - 替换字符串中的所有逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10610402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Replace all commas in a string
提问by mike
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)
Result: "thisnewcharis,a,test"
结果:"thisnewcharis,a,test"
The documentation indicates that the default replaces all, and that "-1" also indicates to replace all, but it is unsuccessful. Any thoughts?
文档说明默认替换全部,“-1”也表示替换全部,但是不成功。有什么想法吗?
回答by VisioN
The third parameter of String.prototype.replace()
function was never defined as a standard, so most browsers simply do not implement it.
String.prototype.replace()
function的第三个参数从未被定义为标准,因此大多数浏览器根本没有实现它。
The best way is to use regular expressionwith g
(global) flag.
最好的方法是使用带有( global) 标志的正则表达式。g
var myStr = 'this,is,a,test';
var newStr = myStr.replace(/,/g, '-');
console.log( newStr ); // "this-is-a-test"
Still have issues?
还有问题吗?
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"
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.
如果您需要将变量作为替换字符串传递,而不是使用正则表达式文字,您可以创建RegExp
对象并将字符串作为构造函数的第一个参数传递。正常的字符串转义规则(\
包含在字符串中时的特殊字符前面)将是必要的。
var myStr = 'this.is.a.test';
var reStr = '\.';
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');
console.log( newStr ); // "this-is-a-test"
回答by RobG
Just for fun:
只是为了好玩:
var mystring = "this,is,a,test"
var newchar = '|'
mystring = mystring.split(',').join(newchar);
回答by gdoron is supporting Monica
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");
Use the global(g
) flag
使用 global( g
) 标志