JavaScript .replace 仅替换第一个匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3214886/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:42:22  来源:igfitidea点击:

JavaScript .replace only replaces first Match

javascriptregexreplace

提问by Yardstermister

var textTitle = "this is a test"
var result = textTitle.replace(' ', '%20');

But the replace functions stops at the first instance of the " " and I get the

但是替换函数在“”的第一个实例处停止,我得到

Result : "this%20is a test"

结果 : "this%20is a test"

Any ideas on where Im going wrong im sure its a simple fix.

关于我哪里出错的任何想法,我确定这是一个简单的修复。

回答by Nick Craver

You need a /gon there, like this:

你需要/g在那里,像这样:

var textTitle = "this is a test";
var result = textTitle.replace(/ /g, '%20');

console.log(result);

You can play with it here, the default .replace()behavior is to replace only the first match, the /gmodifier(global) tells it to replace all occurrences.

你可以用它在这里玩,默认.replace()行为是仅更换第一场比赛,/g改性剂(全球)告诉它全部替换。

回答by Nikita Rybak

textTitle.replace(/ /g, '%20');

回答by J. Holmes

Try using a regex instead of a string for the first argument.

尝试对第一个参数使用正则表达式而不是字符串。

"this is a test".replace(/ /g,'%20')// #=> "this%20is%20a%20test"

"this is a test".replace(/ /g,'%20')// #=> "this%20is%20a%20test"

回答by Subham Debnath

For that you neet to use the g flag of regex.... Like this :

为此,您需要使用正则表达式的 g 标志.... 像这样:

var new_string=old_string.replace( / (regex) /g,  replacement_text);

That sh

那个sh

回答by Jhonny D. Cano -Leftware-

From w3schools

来自 w3schools

The replace() method searches for a matchbetween a substring (or regular expression) and a string, and replaces the matched substring with a new substring

用于替换()方法检索一个匹配的子串(或正则表达式)和一个串之间,并替换匹配用新的子串

Would be better to use a regex here then:

那么在这里使用正则表达式会更好:

textTitle.replace(/ /g, '%20');

回答by Nigrimmist

The same, if you need "generic" regex from string :

同样,如果您需要来自 string 的“通用”正则表达式:

const textTitle = "this is a test";
const regEx = new RegExp(' ', "g");
const result = textTitle.replace(regEx , '%20');
console.log(result); // "this%20is%20a%20test" will be a result
    

回答by amfeng

Try using replaceWith()or replaceAll()

尝试使用replaceWith()replaceAll()

http://api.jquery.com/replaceAll/

http://api.jquery.com/replaceAll/