Noah Crowley
Noah Crowley

Reputation: 455

Recognizing Multple Sets of Opening Tag, Body, and Closing Tag in Regex

I'm attempting to develop a function that converts [bold]...[/bold] into <b>...</b> for my forum. As of right now, this works perfectly when there is only one set of [bold]...[/bold], however, whenever a second one is added, the regex does not recognize the end of the first [bold] until the second.

To illustrate, if I were to put "[bold]Hello[/bold], how are you [bold]today[/bold]?", I should get this:

Hello, how are you today?

However, what I'm actually getting is this:

Hello[/bold], how are you [bold]today?

Below is my current function:

function formatBolds(str) {
    output = output.replace(/(\[bold\])(.*)(\[\/bold\])/g, "<b>$2</b>");
}

Upvotes: 0

Views: 21

Answers (2)

davidrac
davidrac

Reputation: 10738

I think that using a non-greedy match should solve your problem:

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

Upvotes: 3

nu11p01n73R
nu11p01n73R

Reputation: 26667

All you need it to change the .* to non greedy .*?

function formatBolds(str) {
    output = output.replace(/(\[bold\])(.*?)(\[\/bold\])/g, "<b>$2</b>");
}
  • The problem with .* is that its greedy and tries to match as many as characters as possible, includeing the first [/bold] and following [bold] until the last [/bold]. The ? makes it non greedy, and halts the matching at the minimum length match

Upvotes: 3

Related Questions