faressoft
faressoft

Reputation: 19651

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

Upvotes: 3

Views: 1136

Answers (4)

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28830

A regular expression that takes care of removing p attributes

var new = text.replace(/^<p[^>]*>(.*)<\/p>$/i, "$1");

Or a version with .*?

var new = text.replace(/^<p.*?>(.*)<\/p>$/i, "$1");


And if <pre> or <param> may start the text, you have to prevent a match

var new = text.replace(/^<p\b.*?>(.*)<\/p>$/i, "$1");


edit to answer your second question

To remove whatever is before / after

var new = text.replace(/^.*<p\b[^>]*>(.*)<\/p>.*$/i, "$1");

But if you want to remove all <p...> and all </p>, you should use the two lines

var new = text.replace(/<p\b.*?>/ig, "");
new = text.replace(/<\/p>/ig, "");

Upvotes: 1

Anurag
Anurag

Reputation: 141869

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.

Upvotes: 12

Josh K
Josh K

Reputation: 28883

Note I used p> and </p instead of the full tag. I'm not sure if the split will give you an array with an empty first index if you use the full tag. I'm too lazy to test it given the rather poor question phrasing.

var text = "<p><span>Hello</span></p>";
var foo = text.split("p>");
var bar = foo[1].split("</p");
alert(bar[0]);

Upvotes: -1

Paul Schreiber
Paul Schreiber

Reputation: 12589

What do you really want?

  • You can pull this out with a substring: text.substr(3, 18)
  • You can use a regex: text.match(/<span>([^<]+)<\/span>/)
  • You can stick this is the DOM and parse it out.

You'll need to explain the question better.

Upvotes: 0

Related Questions