Reputation: 455
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
Reputation: 10738
I think that using a non-greedy match should solve your problem:
(\[bold\])(.*?)(\[\/bold\])
Upvotes: 3
Reputation: 26667
All you need it to change the .*
to non greedy .*?
function formatBolds(str) {
output = output.replace(/(\[bold\])(.*?)(\[\/bold\])/g, "<b>$2</b>");
}
.*
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 matchUpvotes: 3