为什么javascript在使用replace时只替换第一个实例? [英] Why does javascript replace only first instance when using replace?

查看:90
本文介绍了为什么javascript在使用replace时只替换第一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个

 var date = $('#Date').val();

这得到文本框中的值看起来像这样

this get the value in the textbox what would look like this

12/31/2009

12/31/2009

现在我就这样做了

var id = 'c_' + date.replace("/", '');

,结果是

c_1231 / 2009

c_1231/2009

它错过了最后一个'/'我不明白为什么。

It misses the last '/' I don't understand why though.

推荐答案

您需要设置 g flag 全局替换:

You need to set the g flag to replace globally:

date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')

否则只会替换第一次出现。

Otherwise only the first occurrence will be replaced.

这篇关于为什么javascript在使用replace时只替换第一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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