简体   繁体   中英

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.

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:

  1. The first part (?:^<p[^>]*>) uses the caret ^ character to match the start of the string,
  2. then <p will match the start of the opening p tag,
  3. [^>]* will match any character except the > character,
  4. the | splits the expression into two, one in each pair of braces where either can be matched,
  5. the <\\/p>$ expression will match a closing </p> tag only if it is right at the end of the string by using the $ character.

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('<')));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM