JavaScript .replace只替换第一个匹配

Yar*_*ter 110 javascript regex replace

var textTitle = "this is a test"
var result = textTitle.replace(' ', '%20');
Run Code Online (Sandbox Code Playgroud)

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

结果: "this%20is a test"

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

Nic*_*ver 208

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

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

console.log(result);
Run Code Online (Sandbox Code Playgroud)

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

  • 确实需要什么.谢谢. (3认同)

Nig*_*ist 8

同样,如果您需要 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
    
Run Code Online (Sandbox Code Playgroud)


Nik*_*bak 7

textTitle.replace(/ /g, '%20');
Run Code Online (Sandbox Code Playgroud)


Jho*_*re- 5

来自 w3schools

Replace() 方法搜索子字符串(或正则表达式)和字符串之间的匹配项,并将匹配的子字符串替换为新的子字符串

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

textTitle.replace(/ /g, '%20');
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

89789 次

最近记录:

6 年,2 月 前