Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

javascript - JavaScript-替换字符串中的所有逗号[重复](JavaScript - Replace all commas in a string [duplicate])

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?

(有什么想法吗?)

  ask by mike translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...