1

I have string with value = "[1] a [2] b [3] c" in Javascript. I would like to replace it to "a b c".

My question is how to do it in Javascript by using Regex?

I have tried the following but no luck:

var strText = "[1] a [2] b [3] c";
var strTextReplaced = strText.replace(new RegExp("\[/d\] ", ""), "");
0

2 Answers 2

2

Using regular expression /\[\d+\]/g:

> var value = "[1] a [2] b [3] c";
> value.replace(/\[\d+\]/g, '')
" a  b  c"
  • \d instead of /d.
  • Escape [ and ].

Use /\[\d+\]\s*/ if you want remove extra spaces.

Sign up to request clarification or add additional context in comments.

4 Comments

I'd use /\[\d+\]\s*/ to remove extra spaces.
@M42, I mentioned that. Thank you.
rigth. I give you +1.
I think that last asterisk should be a plus. The original request said they wanted to match '[1] ', and this proposition will also match '[1]' without the trailing space (although given it's a greedy match, you'll likely not notice this during testing).
0

It's \d instead of /d, and you need to escape the special characters with \ as well. Also, you need the "g" or global flag which allows more than one replacement.

In JavaScript the \ has special meaning. So you need to escape it as well.

strText.replace(new RegExp("\\[\\d\\]", "g"), "")

Because of the nusiance of that, JavaScript has this shorthand version of the above.

strText.replace(/\[\d\]/g, "")

Technically you only need to escape the [, but not the ].

strText.replace(/\[\d]/g, "")

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.