Michael Jones
Michael Jones

Reputation: 2282

Don't Grab Word With Regex If It Has Tags Around It JS

I am having trouble with this regex, and TBH I am not even sure if it possible.

Ok so basically if the text has [code] tags around it, the text inside will not be parsed. Let me show you what I mean:

[b]This text will appear bold[/b]
[code] [b]This text will not appear bold, but the bold tags will still be shown[/b] [/code]

So basically I am trying to check and see if the text has [code] tags around it. I have tried this regex:

/((?!\[code\])\[b\](.*)\[\/b\](?!\[\/code\]))/gi

So basically I thought the (?!\[code\]) would not display the text if it had that around it, but it still is not working. So even if the text has [code] around it, the text inside will be higlighted, but the [code] tag will not be. How would I go about ONLY showing the bold if it does not have the code tags around it?

Upvotes: 1

Views: 66

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

To avoid something the way is to match it first and to capture it. To replace text enclosed between [b] tags except when theses tags are between [code] tags, you can write:

txt=txt.replace(/(\[code\][\s\S]*?\[\/code\])|\[b\]([\s\S]*?)\[\/b\]/g, 
    function (m, g1, g2) { return g1 ? g1 : '<b>' + g2 + '</b>'; 
});

So when group 1 exists it is returned without change. When it is not defined the replacement string is returned.

Upvotes: 1

Related Questions