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 &开发者_高级运维amp; 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
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.
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, "");
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.
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]);
精彩评论