I want to remove numbers from a string:
JavaScript
x
2
1
questionText = "1 ding ?"
2
I want to replace the number 1
number and the question mark ?
. It can be any number. I tried the following non-working code.
JavaScript
1
2
1
questionText.replace(/[0-9]/g, '');
2
Advertisement
Answer
Very close, try:
JavaScript
1
2
1
questionText = questionText.replace(/[0-9]/g, '');
2
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:
JavaScript
1
2
1
var withNoDigits = questionText.replace(/[0-9]/g, '');
2
One last trick to remove whole blocks of digits at once, but that one may go too far:
JavaScript
1
2
1
questionText = questionText.replace(/d+/g, '');
2