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

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

questionText = "1 ding ?"

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

questionText.replace(/[0-9]/g, '');
180780 次浏览

非常接近,试试:

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

replace不能处理现有的字符串,它返回一个新的字符串。如果你想用它,你就得留着它!
类似地,您可以使用一个新变量:

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

最后一个技巧是同时删除整个数字块,但这个技巧可能有点过了:

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

你们非常亲密。

这是你在问题中写的代码:

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 = questionText.replace(/[0-9]/g, '');

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

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

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

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

如果你想修剪前面(和后面)的空间:

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

只是想补充一下,因为它可能会引起某人的兴趣,那么你也可以用另一种方式来思考这个问题。我不确定这是否有意义,但我认为它是相关的。

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:

Var strippedText = (“1 ding?”) . place (/[ ^ a-zA-Z ]/g,”) ;

基本上就是“删除任何 a b c d... Z (任何字母)。

这可以在没有 regex的情况下完成,因为 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.

第二个选择是匹配并返回非数字,其表达式类似于,

/\D+/g

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

Demo

测试

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));


如果您希望简化/修改/探索这个表达式,它已经在 regex101.com的右上面板中进行了解释。如果您愿意,您还可以在 这个链接中观察它如何与一些样本输入进行匹配。


正交电路

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

enter image description here

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

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

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.

 const questionText = "1 ding ?";
const res = questionText.replace(/[\W\d]/g, "");
console.log(res);