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, '');
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.
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, '');
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,'');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With