Gerhard
Gerhard

Reputation: 1362

Why my RegEx doesn't replace multiple occurrences?

I would like to remove the "[[" and "]]" from my string with regex in JavaSript (I know it can easily be done with simple replace, but that is not what I want)

var str = "abc [[def]] ghi [[jkl]] mno";
str = str.replace(/\[\[(.*)\]\]/g, "$1");

the resulting string is abc def]] ghi [[jkl mnoinstead of abc def ghi jkl mno What can I do?

Upvotes: 2

Views: 60

Answers (4)

thefourtheye
thefourtheye

Reputation: 239443

The RegEx,

/\[\[(.*)\]\]/

actually says, start from [[, match as many characters as possible (because of the *), till you see ]]. So it actually matches the string,

[[def]] ghi [[jkl]]

and replace it with the matched characters between [[ and ]] which is def]] ghi [[jkl, since it is the maximum possible match. That is why you are getting,

abc def]] ghi [[jkl mno

as the result. To fix this, you need to make the *, non-greedy like this

str = str.replace(/\[\[(.*?)\]\]/g, "$1");

Now, the ? makes * match as minimum as possible. So, it first matches, [[def]] and replaces it with def then it matches [[jkl]] and replaces it with jkl.

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174696

You could simply try this also,

> var str = "abc [[def]] ghi [[jkl]] mno";
> str.replace(/\[\[|\]\]/g, "")
'abc def ghi jkl mno'

The above regex would match [[ or ]] symbols. Replacing those matched characters with empty string will give you the desired output.

Upvotes: 1

antyrat
antyrat

Reputation: 27765

You can do it simpler:

str = str.replace(/[\[\]]/g, "");

var str = "abc [[def]] ghi [[jkl]] mno";
str = str.replace(/[\[\]]/g, "");
alert( str )

Upvotes: 0

vks
vks

Reputation: 67968

str = str.replace(/\[\[(.*?)\]\]/g, "$1");

Make your * non greedy.or

[\[\]]+

Simple replace this by empty string.

Upvotes: 1

Related Questions