Reputation: 8482
I'm trying to build a regular expression to replace brackets with other content, in this case, a div tag..
So, the text:
This is a [sample] text
Would become:
This is a <div>sample</div> text
The problem is, it should only replace when both brackets are found, and keep the content inside. If only one bracket is found, it should ignore it..
So
This is a [sample text
or
This is a ] sample text
Both would remain as is.
Also it should match more than one occurence, so:
This [is] a [sample] [text]
Would become
This <div>is</div> a <div>sample</div> <div>text</div>
And one last thing, it should remove (or at least ignore) nested brackets, so
This [[is a ] sample [[[ tag]]]
Would become
This <div>is a</div> sample <div> tag </div>
This is what I got until now:
function highlightWords(string){
return string.replace(/(.*)\[+(.+)\]+(.*)/,"$1<div>$2</div>$3");
}
It works in simple cases, but won't get multiple occurences and won't remove other tags. Any regex masters around?
Upvotes: 3
Views: 4114
Reputation: 89557
No need to describe content before and after brackets. You must forbid brackets in the content description, so use [^\][]+
instead of .+
. Don't forget to add g
for a global replacement:
function highlightWords(string){
return string.replace(/\[+([^\][]+)]+/g,"<div>$1</div>");
}
Note: you don't need to escape the closing square bracket outside a character class, it isn't a special character.
Upvotes: 8