How to wrap a group of words with tags, JavaScript Replace regular expressions

I am trying to wrap a few words with HTML tags because I use regular expressions. I'm almost there:

This is my regex

/((apple|banana|cherry|orange)\b\s?)+/gi 

and this is my replacement:

 <em>$&</em> 

which works fine for my sample text:

 Apple Banana apple cherry, Cherry orange and Oranges Apple, Banana 

result:

 <em>Apple Banana apple cherry</em>, <em>Cherry orange </em>and Oranges <em>Apple</em>, <em>Banana</em> 

I could be pragmatic and live with it, but I would like it to be perfect and not include space after the final match.

i.e. my ideal result would be (see tag shifted to the left after "Cherry Orange"):

 <em>Apple Banana apple cherry</em>, <em>Cherry orange</em> and Oranges <em>Apple</em>, <em>Banana</em> 
+6
javascript regex replace
source share
3 answers

JavaScript does not support lookbehind. This is a shame, as we could do:

 // doesn't work in JavaScript: /((apple|banana|cherry|orange)\b\s?)+(?<!\s)/gi 

However, we can move the white space to the beginning and add a negative result (so catch should not start with a space):

 /(?!\s)(\s?\b(apple|banana|cherry|orange)\b)+/gi 

The slight difference from your code is that I also added \b to the beginning of the template, so it would not catch apple from Snapple .

+4
source share

You can put the function in the replace parameter as

function(x){return "<em>"+x.replace(/\s+$/,"")+"<em>";} instead of <em>$&</em>

and you can put strip space inside this function.

 "Apple Banana apple cherry, Cherry orange and Oranges Apple, Banana".replace( /((?:apple|banana|cherry|orange)\b\s?)+/gi, function(x){ return "<em>"+x.replace(/\s+$/,"")+"<em>"; }) <em>Apple Banana apple cherry<em>, <em>Cherry orange<em>and Oranges <em>Apple<em>, <em>Banana<em> 
+2
source share

You can also solve this using lookahead at the end of the template to make sure that any match is followed by a space, comma or end of line (this, of course, means that the match will not match if the result is followed by a letter, which would be in case of a problematic example).

Modified match pattern:

 /((apple|banana|cherry|orange)\b\s?)+(?=\s|,|$)/gi 
0
source share

All Articles