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, '');
Solution 1:
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, '');
Solution 2:
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,'');