Back to the lesson

Find bbtag pairs

A “bb-tag” looks like [tag]...[/tag], where tag is one of: b, url or quote.

For instance:

[b]text[/b]
[url]http://google.com[/url]

BB-tags can be nested. But a tag can’t be nested into itself, for instance:

Normal:
[url] [b]http://google.com[/b] [/url]
[quote] [b]text[/b] [/quote]

Impossible:
[b][b]text[/b][/b]

Tags can contain line breaks, that’s normal:

[quote]
  [b]text[/b]
[/quote]

Create a regexp to find all BB-tags with their contents.

For instance:

let reg = /your regexp/g;

let str = "..[url]http://google.com[/url]..";
alert( str.match(reg) ); // [url]http://google.com[/url]

If tags are nested, then we need the outer tag (if we want we can continue the search in its content):

let reg = /your regexp/g;

let str = "..[url][b]http://google.com[/b][/url]..";
alert( str.match(reg) ); // [url][b]http://google.com[/b][/url]

Opening tag is \[(b|url|quote)\].

Then to find everything till the closing tag – let’s the pattern [\s\S]*? to match any character including the newline and then a backreference to the closing tag.

The full pattern: \[(b|url|quote)\][\s\S]*?\[/\1\].

In action:

let reg = /\[(b|url|quote)\][\s\S]*?\[\/\1\]/g;

let str = `
  [b]hello![/b]
  [quote]
    [url]http://google.com[/url]
  [/quote]
`;

alert( str.match(reg) ); // [b]hello![/b],[quote][url]http://google.com[/url][/quote]

Please note that we had to escape a slash for the closing tag [/\1], because normally the slash closes the pattern.