Removing numbers from a string?

removing numbers from a string

questionText = "1 ding ?" 

I want to replace this number and the question number, the number can be any number, I tried using the following code that does not work

  questionText.replace(/[0-9]/g, ''); 
+46
javascript regex
Feb 14 2018-11-11T00:
source share
4 answers

Very close, try:

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

replace does not work on an existing string, it returns a new one. If you want to use it, you need to save it!
Similarly, you can use the new variable:

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

One final trick to immediately remove whole blocks of numbers, but you can go too far:

 questionText = questionText.replace(/\d+/g, ''); 
+91
Feb 14 2018-11-11T00:
source share

String is immutable , so questionText.replace(/[0-9]/g, ''); works on it, but does not change the questionText line. You will have to assign the result of replacing another String variable or the questionText itself.

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

or 1 time (using \d+ , see Kobe's answer):

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

and if you want to crop the leading (and final) space (s) while you are on it:

  questionText = ("1 ding ?").replace(/\d+|^\s+|\s+$/g,''); 
+9
Feb 14 '11 at 15:34
source share

You are amazingly close.

Here is the code you wrote in the question:

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

The code you wrote really looks at the questionText variable and produces the output, which is the original string, but replacing the digits with an empty string.

However, it does not automatically assign it to the original variable. You need to indicate what to assign to it:

 questionText = questionText.replace(/[0-9]/g, ''); 
+8
Feb 14 2018-11-14T00:
source share

Just want to add, as it may be interesting to someone that you can think about a problem and vice versa. I'm not sure if this is interesting, but I find it relevant.

What I mean by another way is to say "drop everything that is not what I am looking for, that is, if you want only" ding ", you could say:

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

Which basically means "delete everything that is nog a, b, c, d .... Z (any letter).

+1
Mar 05 2018-12-12T00:
source share



All Articles