JavaScript .replace 仅替换第一个匹配项 [英] JavaScript .replace only replaces first Match

查看:32
本文介绍了JavaScript .replace 仅替换第一个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

结果:this%20is a test"

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

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

推荐答案

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

You need a /g on there, like this:

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

console.log(result);

你可以在这里玩,默认的 .replace() 行为是只替换第一个匹配项,/g 修饰符(全局)告诉它替换所有出现的.

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

这篇关于JavaScript .replace 仅替换第一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆