How to remove numbers from a string?

JavascriptRegex

Javascript Problem Overview


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, '');

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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,'');

Solution 3 - Javascript

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, '');

Solution 4 - Javascript

You can use .match && join() methods. .match() returns an array and .join() makes a string

function digitsBeGone(str){
  return str.match(/\D/g).join('')
}

Solution 5 - Javascript

Just want to add since it might be of interest to someone, that you may think about the problem the other way as well. I am not sure if that is of interest here, but I find it relevant.

What I mean by the other way is to say "strip anything that aren't what I am looking for, i.e. if you only want the 'ding' you could say:

var strippedText = ("1 ding ?").replace(/[^a-zA-Z]/g, '');

Which basically mean "remove anything which is nog a,b,c,d....Z (any letter).

Solution 6 - Javascript

A secondary option would be to match and return non-digits with some expression similar to,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

##Demo

##Test

function non_digit_string(str) {
	const regex = /\D+/g;
	let m;

	non_digit_arr = [];
	while ((m = regex.exec(str)) !== null) {
		// This is necessary to avoid infinite loops with zero-width matches
		if (m.index === regex.lastIndex) {
			regex.lastIndex++;
		}


		m.forEach((match, groupIndex) => {
			if (match.trim() != '') {
				non_digit_arr.push(match.trim());
			}
		});
	}
	return non_digit_arr;
}

const str = `1 ding ? 124
12 ding ?
123 ding ? 123`;
console.log(non_digit_string(str));


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Solution 7 - Javascript

This can be done without regex which is more efficient:

var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
	num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);

And as a bonus, it also stores the number, which may be useful to some people.

Solution 8 - Javascript

Just want to add since it might be of interest to someone, that you may think about the problem the other way as well. I am not sure if that is of interest here, but I find it relevant.

 const questionText = "1 ding ?";
    const res = questionText.replace(/[\W\d]/g, "");
    console.log(res);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkiranView Question on Stackoverflow
Solution 1 - JavascriptKobiView Answer on Stackoverflow
Solution 2 - JavascriptKooiIncView Answer on Stackoverflow
Solution 3 - JavascriptSpudleyView Answer on Stackoverflow
Solution 4 - JavascriptcaptainozlemView Answer on Stackoverflow
Solution 5 - JavascriptqrikkoView Answer on Stackoverflow
Solution 6 - JavascriptEmmaView Answer on Stackoverflow
Solution 7 - JavascriptDan BrayView Answer on Stackoverflow
Solution 8 - JavascriptMohsin GhaziView Answer on Stackoverflow