Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and replace text inside quotes ignoring html tags

I have simple text with HTML tags and some text in quotation marks I want to add span on text inside quotes. for example:

<p>A quick "brown" fox "jumps" over <a href="www.gamescottage.com">the</a> lazy dog.</p>

And I want is to change this line to something like this:

<p>A quick "<span>brown</span>" fox "<span>jumps</span>" over <a href="www.gamescottage.com">the</a> lazy dog.</p>

and I am using this this code to do this :

<script>
    $('document').ready(function (){
        var text = $('p').html();
        text = text.replace(/"(.*?)"/g, '"<span class="quote">$1</span>"');
        $('p').html(text);
     });
</script>

but it replace quotes of HTML anchor tag as well any solution? In short I just want to add span inside quotes ignoring quotes of HTML tags.

like image 547
Husnain Ali Avatar asked Sep 09 '14 10:09

Husnain Ali


2 Answers

JavaScript already has a built on DOM parser for you - instead of trying to parse HTML with a regular expression which is inherently difficult and borderline impossible - you can use the built in abilities the DOM brings you. In your case I'll demonstrate it using jQuery but a non-jQuery solution is equally simple:

$("p"). // all p tags
contents(). // select the actual contents of the tags 
filter(function(i,el){   return el.nodeType === 3; }). // only the text nodes
each(function(i, el){ 
    var $el = $(el); // take the text node as a jQuery element
    var replaced = $el.text().replace(/"(.*?)"/g,'<span>"$1"</span>') // wrap
    $el.replaceWith(replaced); // and replace
});

Here's a fiddle.

like image 54
Benjamin Gruenbaum Avatar answered Oct 13 '22 10:10

Benjamin Gruenbaum


You could do this in three separate steps:

  1. temporarily replace quotes in HTML tags with a marker
  2. add spans to any remaining quotes
  3. restore quotes where any markers were put

Step 1:

text = text.replace(/([^>"]*)"(?=[^<]*>)/g, '$1#Q#');

This uses a lookahead to see whether the quote is followed by a > before the next <

Step 2:

text = text.replace(/"(.*?)"/g, '<span class="quote">$1</span>');

Step 3:

text = text.replace(/#Q#/g, '"');

like image 33
Brian Stephens Avatar answered Oct 13 '22 09:10

Brian Stephens