How to remove numbers from a string?
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,'');
You're remarkably close.
Here's the code you wrote in the question:
questionText.replace(/[0-9]/g, '');
The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.
However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:
questionText = questionText.replace(/[0-9]/g, '');