[英]In Javascript or jQuery, how do I remove only the first and last tag?
given the following string: 给出以下字符串:
var htmlStr = '<p class="red_349dsa01">This is</p><p class="blue_saf9vsaz">a test</p>';
how can I remove the very first and last tag off this string? 如何删除此字符串中的第一个和最后一个标记? This would be the result:
这将是结果:
var htmlStr = 'This is</p><p class="blue_saf9vsaz">a test';
I know this will create invalid HTML, but I just want to know if this can be done at all. 我知道这会创建无效的HTML,但我只想知道是否可以完成此操作。
You would need a regular expression here: 你需要一个正则表达式:
var regex = /(?:^<p[^>]*>)|(?:<\/p>$)/g;
var htmlStr = '<p class="red_349dsa01">This is</p><p class="blue_saf9vsaz">a test</p>';
htmlStr.replace(regex, "");
An explanation of the regex: 正则表达式的解释:
(?:^<p[^>]*>)
uses the caret ^
character to match the start of the string, (?:^<p[^>]*>)
使用插入符^
字符来匹配字符串的开头, <p
will match the start of the opening p
tag, <p
将匹配开始p
标签的开头, [^>]*
will match any character except the >
character, [^>]*
将匹配除>
字符之外的任何字符, |
|
splits the expression into two, one in each pair of braces where either can be matched, <\\/p>$
expression will match a closing </p>
tag only if it is right at the end of the string by using the $
character. <\\/p>$
表达式只有在字符串末尾使用$
字符时才会匹配结束</p>
标记。 You could try something like 你可以试试像
var htmlStr = '<p class="red_349dsa01">This is</p><p class="blue_saf9vsaz">a test</p>';
alert(htmlStr.substring(htmlStr.indexOf('>') + 1, htmlStr.lastIndexOf('<')));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.