0

I have this string:

whatever [that's the pattern] by [pattern again] before [whatever].

I would love to wrap the brackets [] and everthing inside them in a span to be like:

whatever <span>[that's the pattern]</span> by </span>[pattern again]</span>
before <span>[whatever]</span>.

I have tried

re = new RegExp(/\[(.*)\]/);
var newString =  oldString.replace(re, "<span>$1</span>");

But this returns:

whatever <span>[that's the pattern] by [pattern again] before [whatever]</span>.

Before anyone shoot me about why shouldn't I use regex to parse HTML, the reason I am doing this is because this string is echoed on the web page and the brackets and the text within has different color. I need to wrap them in a span to be able to style them. If there's a better solution I am open.

Many thanks!

Community
  • 1
  • 1
Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99

2 Answers2

2

Aside from setting the global flag, you also need to make your regex lazy:

var newString = oldString.replace(/\[(.*?)\]/g, "<span>[$1]</span>")
                                        ^    ^
Jerry
  • 70,495
  • 13
  • 100
  • 144
  • Many thanks, this is exactly what I needed. What do you mean by making regex lazy? If I understand well, this will make it stop to check if every character match? – Ahmad Alfy Jun 03 '13 at 17:39
  • 1
    @AhmadAlfy It will match the **minimum**, as opposed to the **maximum** (greedy). I'm not too sure about the exact matching process though, sorry ^^; You'll see that in your original regex, it matched everything till the last `]`, that's what's greedy. – Jerry Jun 03 '13 at 17:46
1

You need to set the global flag, which tells it to match more than once:

oldString.replace(/\[(.*)\]/g, ...)
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964