125

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, '');
3
  • 3
    What exactly is not working? Because it IS removing the number... Commented Feb 14, 2011 at 15:13
  • Will you also need to remove decimal points? Commented Feb 14, 2011 at 16:19
  • 1
    @Berbi This question is not duplicate. The cited one "Replace method does't work" doesn't have a proper title so that a user can type in and search for "Removing numbers from string". Bad moderation. Commented Dec 12, 2014 at 14:54

9 Answers 9

236

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, '');
Sign up to request clarification or add additional context in comments.

3 Comments

can i replace ? & * from a string in one replace methode like str.replace("?,*", " ");
that is not working , i wan to replace both ? and * with space in my string
@kiran - remember to escape them, for example \?,\*, but you probably want /[?*]/g. Feel free to ask a new question when you have one!
21

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

1 Comment

Don't forget /g on all regexes - JavaScript is annoying that way :)
13

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

Comments

3

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

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

Comments

2

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).

Comments

1

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

Comments

1

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

Comments

0

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.

Comments

0

Try this, This can be done without regex which is more efficient:

let questionText = "0 ding ?"
let num = [...questionText].map((e, i) => (+e || e == '0')? '' : e).join('')

console.log(num)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.