Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove numbers from a string?

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, ''); 
like image 277
kiran Avatar asked Feb 14 '11 15:02

kiran


People also ask

How do I remove a specific number of characters in a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

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, ''); 
like image 68
Kobi Avatar answered Oct 21 '22 21:10

Kobi


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,''); 
like image 33
KooiInc Avatar answered Oct 21 '22 22:10

KooiInc