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

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

How to remove numbers from a string?

javascriptregex

提问by kiran

I want to remove numbers from a string:

我想从字符串中删除数字:

questionText = "1 ding ?"

I want to replace the number 1number and the question mark ?. It can be any number. I tried the following non-working code.

我想替换数字1number 和问号?。它可以是任何数字。我尝试了以下非工作代码。

questionText.replace(/[0-9]/g, '');

回答by Kobi

Very close, try:

非常接近,尝试:

questionText = questionText.replace(/[0-9]/g, '');

replacedoesn't work on the existing string, it returns a new one. If you want to use it, you need to keep it!
Similarly, you can use a new variable:

replace不适用于现有字符串,它返回一个新字符串。如果你想使用它,你需要保留它!
同样,您可以使用一个新变量:

var withNoDigits = questionText.replace(/[0-9]/g, '');

One last trick to remove whole blocks of digits at once, but that one may go too far:

一次删除整块数字的最后一个技巧,但可能走得太远了:

questionText = questionText.replace(/\d+/g, '');

回答by KooiInc

String are immutable, that's why questionText.replace(/[0-9]/g, '');on it's own doeswork, but it doesn't change the questionText-string. You'll have to assign the result of the replacement to another String-variable or to questionText itself again.

String 是不可变的,这就是为什么questionText.replace(/[0-9]/g, '');它自己可以工作,但它不会改变 questionText-string。您必须将替换结果分配给另一个字符串变量或再次分配给 questionText 本身。

var cleanedQuestionText = questionText.replace(/[0-9]/g, '');

or in 1 go (using \d+, see Kobi's answer):

或 1 次(使用\d+,请参阅 Kobi 的回答):

 questionText = ("1 ding ?").replace(/\d+/g,'');

and if you want to trim the leading (and trailing) space(s) while you're at it:

如果您想在使用时修剪前导(和尾随)空格:

 questionText = ("1 ding ?").replace(/\d+|^\s+|\s+$/g,'');

回答by Spudley

You're remarkably close.

你非常接近。

Here's the code you wrote in the question:

这是您在问题中编写的代码:

questionText.replace(/[0-9]/g, '');

The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.

您编写的代码确实查看了 questionText 变量,并生成了原始字符串的输出,但数字替换为空字符串。

However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:

但是,它不会自动将其分配回原始变量。您需要指定将其分配给什么:

questionText = questionText.replace(/[0-9]/g, '');

回答by qrikko

Just want to add since it might be of interest to someone, that you may think about the problem the other way as well. I am not sure if that is of interest here, but I find it relevant.

只是想补充一下,因为有人可能会对它感兴趣,所以您也可以以另一种方式思考问题。我不确定这是否对这里感兴趣,但我觉得它相关。

What I mean by the other way is to say "strip anything that aren't what I am looking for, i.e. if you only want the 'ding' you could say:

我用另一种方式的意思是说“去掉任何不是我要找的东西,即如果你只想要 'ding',你可以说:

var strippedText = ("1 ding ?").replace(/[^a-zA-Z]/g, '');

var strippedText = ("1 ding ?").replace(/[^a-zA-Z]/g, '');

Which basically mean "remove anything which is nog a,b,c,d....Z (any letter).

这基本上意味着“删除任何 nog a,b,c,d....Z(任何字母)。

回答by Emma

A secondary option would be to match and return non-digits with some expression similar to,

次要选项是匹配并返回具有类似于以下表达式的非数字,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

这可能适用于问题 ( 1 ding ?)中的特定字符串。

Demo

演示

Test

测试

function non_digit_string(str) {
 const regex = /\D+/g;
 let m;

 non_digit_arr = [];
 while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
   regex.lastIndex++;
  }


  m.forEach((match, groupIndex) => {
   if (match.trim() != '') {
    non_digit_arr.push(match.trim());
   }
  });
 }
 return non_digit_arr;
}

const str = `1 ding ? 124
12 ding ?
123 ding ? 123`;
console.log(non_digit_string(str));



If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

如果你想简化/修改/探索表达式,它已经在regex101.com 的右上角面板中进行了解释。如果您愿意,您还可以在此链接中观看它如何与某些示例输入匹配。



RegEx Circuit

正则表达式电路

jex.imvisualizes regular expressions:

jex.im可视化正则表达式:

enter image description here

在此处输入图片说明

回答by captainozlem

You can use .match && join() methods. .match() returns an array and .join() makes a string

您可以使用 .match && join() 方法。.match() 返回一个数组, .join() 生成一个字符串

function digitsBeGone(str){
  return str.match(/\D/g).join('')
}

回答by Dan Bray

This can be done without regexwhich is more efficient:

这可以做到,没有regex哪个更有效:

var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
    num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);

And as a bonus, it also stores the number, which may be useful to some people.

作为奖励,它还存储了号码,这可能对某些人有用。