Javascript JS 正则表达式:替换字符串中的所有数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11328353/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:27:21  来源:igfitidea点击:

JS regex: replace all digits in string

javascriptregex

提问by Keith L.

I need to replace all digits.

我需要替换所有数字。

My function only replaces the first digit.

我的函数只替换第一个数字。

var s = "04.07.2012";
alert(s.replace(new RegExp("[0-9]"), "X")); // returns "X4.07.2012"
                                            // should be XX.XX.XXXX"

回答by Gustav Barkefors

You need to add the "global" flag to your regex:

您需要在正则表达式中添加“全局”标志:

s.replace(new RegExp("[0-9]", "g"), "X")

or, perhaps prettier, using the built-in literal regexp syntax:

或者,也许更漂亮,使用内置的文字正则表达式语法:

.replace(/[0-9]/g, "X")

回答by Joey

Use

s.replace(/\d/g, "X")

which will replace all occurrences. The gmeans global matchand thus will not stop matching after the first occurrence.

这将替换所有事件。该g方法全局匹配,因此不会在第一次出现时,停止匹配。

Or to stay with your RegExpconstructor:

或者留在你的RegExp构造函数中:

s.replace(new RegExp("\d", "g"), "X")

回答by ?mega

The/gmodifier is used to perform a global match (find all matches rather than stopping after the first)

/g修改器用于执行全局匹配(查找所有的比赛,而不是第一后停止)

You can use\dfor digit, as it is shorter than[0-9].

您可以使用\dfor digit,因为它比[0-9].

JavaScript:

JavaScript:

var s = "04.07.2012"; 
echo(s.replace(/\d/g, "X"));

Output:

输出:

XX.XX.XXXX

回答by Mohamed Rasik

find the numbers and then replaced with strings which specified. It is achieved by two methods

找到数字,然后用指定的字符串替换。它是通过两种方法实现的

  1. Using a regular expression literal

  2. Using keyword RegExp object

  1. 使用正则表达式文字

  2. 使用关键字 RegExp 对象

Using a regular expression literal:

使用正则表达式文字:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

**输出:**我的联系电话是XXX。我的年龄是 XXX。

for more details:

更多细节:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

回答by coder

You forgot to add the global operator. Use this:

您忘记添加全局运算符。用这个:

var s = "04.07.2012";
alert(s.replace(new RegExp("[0-9]","g"), "X"));