In Javascript Or Jquery, How Do I Remove Only The First And Last Tag?
given the following string: var htmlStr = '
This is
a test
'; how can I remove the very first and lasSolution 1:
You could try something like
var htmlStr = '<pclass="red_349dsa01">This is</p><pclass="blue_saf9vsaz">a test</p>';
alert(htmlStr.substring(htmlStr.indexOf('>') + 1, htmlStr.lastIndexOf('<')));
Solution 2:
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:
- The first part
(?:^<p[^>]*>)uses the caret^character to match the start of the string, - then
<pwill match the start of the openingptag, [^>]*will match any character except the>character,- the
|splits the expression into two, one in each pair of braces where either can be matched, - the
<\/p>$expression will match a closing</p>tag only if it is right at the end of the string by using the$character.
Post a Comment for "In Javascript Or Jquery, How Do I Remove Only The First And Last Tag?"