简体   繁体   English

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

[英]Removing Numbers from a String using Javascript

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. 我很感激任何帮助。

\\d matches 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 g at 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是一个标志,表示“全局”,这意味着它将替换它找到的所有匹配,而不仅仅是第一个匹配。

Just paste this into your address bar to try it out: 只需将其粘贴到您的地址栏即可试用:

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

\\d indicates a character in the range 0-9, and the + indicates one or more; \\d表示0-9范围内的字符, +表示一个或多个字符; so \\d+ matches one or more digits. 所以\\d+匹配一个或多个数字。 The g is necessary to indicate global matching, as opposed to quitting after the first match (the default behavior). g表示全局匹配,而不是在第一次匹配后退出(默认行为)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM