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.
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.
You could do this in three separate steps:
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, '"');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With