How to split <p> <span> Hello </span> </p> by <span> Hello </span> using javascript

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

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

remember: I don’t know what it contains <p>, I don’t know if it has <p>any attribute or not

I found the answer!

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

thank ring0 and w3schools http://www.w3schools.com/jsref/jsref_obj_regexp.asp

but there's a problem! he does not work with

aa<p><span>Hello</span></p>aa
+3
source share
4 answers

Regular expression that removes attributes p

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

Or version with .*?

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


And if <pre>or <param>can start text, you must prevent a match

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


,

, /

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

<p...> </p>,

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

, 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>"

.

jQuery, :

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

.

+12

?

  • : text.substr(3, 18)
  • : text.match(/<span>([^<]+)<\/span>/)
  • DOM .

.

0

. p> </p . , , . , , .

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

Source: https://habr.com/ru/post/1762107/


All Articles