Javascript 使用Javascript从字符串中删除数字

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

Removing Numbers from a String using Javascript

javascriptjquery

提问by Abs

How do I remove numbers from a string using Javascript?

如何使用 Javascript 从字符串中删除数字?

I am not very good with regex at all but I think I can use with replace to achieve the above?

我对正则表达式不太好,但我认为我可以使用替换来实现上述目的?

It would actually be great if there was something JQuery offered already to do this?

如果 JQuery 已经提供了一些东西来做到这一点,那实际上会很棒吗?

//Something Like this??

var string = 'All23';
string.replace('REGEX', '');

I appreciate any help on this.

我很感激这方面的任何帮助。

回答by nickf

\dmatches any number, so you want to replace them with an empty string:

\d匹配任何数字,因此您想用空字符串替换它们:

string.replace(/\d+/g, '')

I've used the +modifier here so that it will match all adjacent numbers in one go, and hence require less replacing. The gat the end is a flag which means "global" and it means that it will replace ALL matches it finds, not just the first one.

我在+这里使用了修饰符,以便它一次性匹配所有相邻的数字,因此需要较少的替换。将g在年底是一个标志,它意味着“全球”,这意味着它将取代所有匹配发现,不只是第一个。

回答by Mark Rushakoff

Just paste this into your address bar to try it out:

只需将其粘贴到您的地址栏中即可试用:

javascript:alert('abc123def456ghi'.replace(/\d+/g,''))

\dindicates a character in the range 0-9, and the +indicates one or more; so \d+matches one or more digits. The gis necessary to indicate globalmatching, as opposed to quitting after the first match (the default behavior).

\d表示0-9范围内的一个字符,+表示一个或多个;所以\d+匹配一位或多位数字。该g指示是必要的全球性的匹配,而不是在第一场比赛(默认行为)后退出。