JavaScript-替换字符串中的所有逗号[重复]

本文翻译自:JavaScript - Replace all commas in a string [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 4 years ago . 4年前关闭。

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. 该文档指示默认值将替换所有,而“ -1”也指示将替换所有,但未成功。 Any thoughts? 有什么想法吗?


#1楼

参考:https://stackoom.com/question/iWFW/JavaScript-替换字符串中的所有逗号-重复


#2楼

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()函数的第三个参数定义为标准,因此大多数浏览器根本不实现它。

The best way is to use regular expression with g ( global ) flag. 最好的方法是使用带有gglobal )标志的正则表达式

 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 . 如果您需要传递变量作为替换字符串,而不是使用regex文字,则可以创建RegExp对象, 并将字符串作为构造函数的第一个参数传递 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" 


#3楼

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global( g ) flag 使用global( g )标志

Simple DEMO 简单的演示


#4楼

Just for fun: 纯娱乐:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值