Javascript 替换数字中的所有点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4050206/
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
Replace all the dots in a number
提问by s427
I'm trying to replace all dots found in a value entered by the user in an HTML form. For instance I need the entry '8.30' to be converted to '8x30'.
我正在尝试替换用户在 HTML 表单中输入的值中找到的所有点。例如,我需要将条目“8.30”转换为“8x30”。
I have this simple code:
我有这个简单的代码:
var value = $(this).val().trim(); // get the value from the form
value += ''; // force value to string
value.replace('.', 'x');
But it doesn't work. Using the console.log command in Firebug, I can see that the replace command simply does not occur. '8.30' remains the same.
但它不起作用。在 Firebug 中使用 console.log 命令,我可以看到替换命令根本没有发生。“8.30”保持不变。
I also tried the following regexp with no better result:
我还尝试了以下正则表达式,但没有更好的结果:
value.replace(/\./g, 'x');
What am I doing wrong here?
我在这里做错了什么?
回答by Bart Kiers
replace
returns a string. Try:
replace
返回一个字符串。尝试:
value = value.replace('.', 'x'); //
// or
value = value.replace(/\./g, 'x'); // replaces all '.'
回答by sgrillon
You have three solutions:
你有三个解决方案:
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');