【问题标题】:Replace all the dots in a number替换数字中的所有点
【发布时间】:2011-05-02 07:14:18
【问题描述】:

我正在尝试替换用户在 HTML 表单中输入的值中找到的所有点。 例如,我需要将条目“8.30”转换为“8x30”。

我有这个简单的代码:

var value = $(this).val().trim(); // get the value from the form
value += ''; // force value to string
value.replace('.', 'x');

但它不起作用。在 Firebug 中使用 console.log 命令,我可以看到 replace 命令根本不会发生。 “8.30”保持不变。

我还尝试了以下正则表达式,但没有更好的结果:

value.replace(/\./g, 'x');

我在这里做错了什么?

【问题讨论】:

  • value.replace(/\./g, 'x');是正确的,它对我有用[我已经检查了 firbug 控制台,例如"2312.88.12.1232".replace(/\./g, 'x');
  • @Chinmayee:是的,它确实有效。正如 Bart Kiers(下)所指出的,我只是忘记了它不会自动更新我的变量中的值。

标签: javascript replace


【解决方案1】:

replace 返回一个字符串。试试:

value = value.replace('.', 'x');   //
                                   // or
value = value.replace(/\./g, 'x'); // replaces all '.'

【讨论】:

  • 这太明显了。 ;) 非常感谢。 :)
【解决方案2】:

你有三个解决方案:

var text= "ABC.DEF.XYZ";
response = text.replace(/\./g,'x');


var text= "ABC.DEF.XYZ";
response = text.replace(new RegExp("\\.","gm"),"x");


var text= "ABC.DEF.XYZ";
response = text.split('.').join('x');

DEMO in JSFIDDLE

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2011-03-09
    相关资源
    最近更新 更多