120

I want to remove numbers from a string:

questionText = "1 ding ?"

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

questionText.replace(/[0-9]/g, '');
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
kiran
  • 1,233
  • 2
  • 9
  • 11

8 Answers8

229

Very close, try:

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

replace doesn'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:

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, '');
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • can i replace ? & * from a string in one replace methode like str.replace("?,*", " "); – kiran Feb 16 '11 at 13:56
  • that is not working , i wan to replace both ? and * with space in my string – kiran Feb 16 '11 at 14:00
  • @kiran - remember to escape them, for example `\?,\*`, but you probably want `/[?*]/g`. Feel free to [ask a new question](http://stackoverflow.com/questions/ask) when you have one! – Kobi Feb 16 '11 at 15:46
19

Strings are immutable, that's why questionText.replace(/[0-9]/g, ''); on it's own does work, 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.

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

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

 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,'');
KooiInc
  • 119,216
  • 31
  • 141
  • 177
12

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.

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, '');
Spudley
  • 166,037
  • 39
  • 233
  • 307
3

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

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

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:

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

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

qrikko
  • 2,483
  • 2
  • 22
  • 35
1

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 ?).

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.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
1

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);
Mohsin Ghazi
  • 79
  • 1
  • 2
  • 6
0

This can be done without regex which is more efficient:

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.

Dan Bray
  • 7,242
  • 3
  • 52
  • 70