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
355 views
in Technique[技术] by (71.8m points)

javascript - 替换字符串中所有字符实例的最快方法(Fastest method to replace all instances of a character in a string)

What is the fastest way to replace all instances of a string/character in a string in JavaScript?(用JavaScript替换字符串中所有字符串/字符实例的最快方法是什么?)

A while , a for -loop, a regular expression?(while ,一个for循环,一个正则表达式?)   ask by Anri?tte Myburgh translate from so

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

1 Reply

0 votes
by (71.8m points)

The easiest would be to use a regular expression with g flag to replace all instances:(最简单的方法是使用带有g标志的正则表达式替换所有实例:)

str.replace(/foo/g, "bar") This will replace all occurrences of foo with bar in the string str .(这将用字符串str bar替换所有出现的foo 。) If you just have a string, you can convert it to a RegExp object like this:(如果只有字符串,可以将其转换为RegExp对象,如下所示:) var pattern = "foobar", re = new RegExp(pattern, "g");

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

...