0

I have following JS -

var pattern = new RegExp("(\\b" + value + "\\b)", 'gi')
if (pattern.test(text)) {
    text = text.replace(pattern, "<span class='class1'>$1</span>");
}

(e.g. value = 'text', text = 'Simple text <span class='class1'>simple text</span> text.')

with this JS I wrapp all 'text' words with span tag. But in this case I will have second 'text' word double wrapped with span tag. I need to replace all words that are equal Value variable but if this word is already in the span with Class1 I need to skip this word.

EXAMPLE: Initial text was: "When using alternative, the order is important since the matching algorithm will attempt to match the leftmost alternative first.". I need to wrap all 'using alternatives' and 'alternatives' words. First we replace 'using alternatives', the result will be:

"When <span class="class1">using alternative</span>, the order is important since the matching algorithm will attempt to match the leftmost alternative first."

Then we replace "alternative":

"When <span class="class1">using <span class="class1">alternative</span></span>, the order is important since the matching algorithm will attempt to match the leftmost <span class="class1">alternative</span> first.".

So I have first "alternative" wrapped with 2 span tags. And I do not need that second tag for "alternative", it is enough to have 'using alternative'.

Sanya530
  • 1,209
  • 4
  • 18
  • 24
  • 2
    Rule 1, don't parse HTML with RegEx. Rule 2, if you want to use RegEx to parse HTML see Rule 1 (With apologies to the original author) – freefaller Sep 04 '13 at 14:50
  • Ahh! I see, so you want to wrap `text` only if it is not already wrapped ? – Ibrahim Najjar Sep 04 '13 at 14:50
  • Yes. If 'text' is not already in the span I want to wrap it with the span. Also if span has not only 'text' e.g. 'text word' this 'text' also should not be wrapped. – Sanya530 Sep 04 '13 at 14:53
  • @Sanya530 can you post a sample HTML of where your value is displayed without the span? – Prix Sep 04 '13 at 14:57
  • 1
    **Don't use regular expressions to parse HTML. Use a proper HTML parsing module.** You cannot reliably parse HTML with regular expressions, and you will face sorrow and frustration down the road. As soon as the HTML changes from your expectations, your code will be broken. See http://htmlparsing.com/php or [this SO thread](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged. – Andy Lester Sep 04 '13 at 15:00
  • I added an example to the question. – Sanya530 Sep 04 '13 at 15:44
  • See also: http://stackoverflow.com/a/1732454/1053021 – michaelb958--GoFundMonica Sep 06 '13 at 06:07

0 Answers0