Monday, February 21, 2011

how to add markup to text using JavaScript regex

I need to add markup to some text using JavaScript regular expressions. In Python I could do this with:

>>> import re
>>> re.sub('(banana|apple)', r'<b>\1</b>', 'I have 1 banana and 2 apples!')
'I have 1 <b>banana</b> and 2 <b>apple</b>s!'

What is the equivalent in JavaScript? string.replace(regex, newstring) seems to only take a raw string for replacing.

From stackoverflow
  • In the new string, you can reference capture groups via the tokens $1, $2, etc. A lot of the high-level reference sites (like w3schools) fail to document that. It's in the spec, of course, or more accessibly discussed on MDC.

    So taking your example:

    "I have 1 banana and 2 apples!".replace(/(banana|apple)/gi, "<b>$1</b>");
    

    (Of course, the "s" in "apples" won't be inside the tag...) I used the 'i' flag there assuming you want to process "Banana" and "Apple" as well as "banana" and "apple".

    Plumo : thanks - I was working from the w3schools documentation
    T.J. Crowder : @Richard: Glad to help. Amusingly, I was surprised when I ran across this feature of #replace...because I, too, had been working from the w3schools pages. :-) Those pages are useful, but really *really* incomplete, so I work from the spec and MDC a lot more now.
    Plumo : wow the Mozilla JavaScript documentation is so detailed! - I will have to get into the habit of checking there first.
  • You can use String.replace() for this and use $n to reference captured groups from the regular expression:

    var in = 'I have 1 banana and 2 apples!';
    var out = in.replace(/(banana|apple)/g, "<b>$1</b>");
    

0 comments:

Post a Comment