Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split <p><span>Hello</span></p> to <span>Hello</span> using javascript

how to split <p><span>Hello</span></p> to <span>Hello</span> using javascript

var text = "<p><span>Hello</span></p>";

remember:I don't know what contain <p>, I don't know if <p> has any attribute or not

I found the answer !

var patt=/^<p.*?>(.*)<\/p>$/i;
var result=patt.exec(text);
alert(result[1]); 

thank's ring0 & w3schools http://www.w3schools.com/jsref/jsref_obj_regexp.asp

but there is problem ! it doesn't work with

aa<p><span>Hello</span></p>aa
like image 724
faressoft Avatar asked Apr 08 '26 08:04

faressoft


1 Answers

Don't do string manipulations on this, make use of the DOM.

// create a dummy container div element
var tempDiv = document.createElement('div');
// insert the desired html inside this container
tempDiv.innerHTML = "<p><span>Hello</span></p>";
// find the first para, and get its html
tempDiv.getElementsByTagName("p")[0].innerHTML; // contains "<span>Hello</span>"

Try this snippet.

If you are using a framework like jQuery, you can use:

$("<p><span>Hello</span></p>").html()

Try this snippet.

like image 192
Anurag Avatar answered Apr 09 '26 20:04

Anurag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!