JavaScript - 替换字符串中的所有逗号 [英] JavaScript - Replace all commas in a string

查看:33
本文介绍了JavaScript - 替换字符串中的所有逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个逗号的字符串,而字符串替换方法只会更改第一个:

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"

文档说明默认替换全部,-1"也表示替换全部,但是不成功.有什么想法吗?

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"

需要注意的是,正则表达式使用 需要转义的特殊字符.例如,如果您需要对点 (.) 字符进行转义,则应使用 /./ 文字,因为在正则表达式语法中,点匹配任何单个字符(行终止符除外).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆