简体   繁体   中英

Javascript Regex to replace brackets with content inside

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM