I have a string that contains variable HTML content. The string can contain one, more or no p tags which may also have classes on them.
What is the best way to remove all p tags from this using jQuery while keeping the HTML content of each of them.
I first tried the following but of course this only works if I have the whole string wrapped in a paragraph and it would not cover if the paragraphs have classes or other attributes on them:
str.substring(3).slice(0, -4);
Here is an example but the number of p tags can vary and there can also be none at all.
Example before:
<p>Some text <p class="someClass"> Some other text</p> Some more text</p>
Example after:
"Some text Some other text Some more text"
You could use a regular expression to do this. It only removes the p-tags and leaves all other tags in place.
JavaScript
var string = "<p>this is a test with <p class='bold'>multiple</p> p-tags.</p><span>THIS IS COOL</span>";
var result = string.replace(/<[\/]{0,1}(p)[^><]*>/ig,"");
console.log(result);
If you'd like to remove all tags, you could use /(<([^>]+)>)/ig
instead as regex.
Try the following:
var str = "<p>Test</p>";
var res = str.replace("<p>", "").replace("</p>", "");
如果我理解正确,并且您希望删除 p 标签但内容仍然存在,那么它应该很简单:
str.replace('<p>', '').replace('</p>', '');
您还可以使用 replaceWith - jsFiddle Example ,可读并与父/子标签一起使用
$('p').replaceWith($('p').text())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.