Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove tag from HTML String without RegEx

So I have following string:

var s = '<span>Some Text</span> Some other Text';

The result should be a string with the content "Some other Text".

I tried...

var $s = $(s).not('span');

...and a lot of other stuff with remove(), not(), etc. but nothing worked.

Any suggestions? I could match the string with regex, but I prefer a common jQuery solution.

edit:

I do not search a solution with regex, I'm just wondering why this example does not work: http://jsfiddle.net/q9crX/150/

like image 698
Fidelis Avatar asked Sep 10 '25 03:09

Fidelis


2 Answers

You can wrap your string in a jQuery object and do some sort of a manipulation like this:

var removeElements = function(text, selector) {
    var wrapped = $("<div>" + text + "</div>");
    wrapped.find(selector).remove();
    return wrapped.html();
}

USAGE

var removedSpanString = removeElements("<span>Some Text</span> Some other Text", "span");

The beauty of this approach is that you can specify a jquery selector which to remove. i.e. you may wish to remove the <th> in a string. This would be very handy in that case. Hope this helps!

like image 155
Abdul Munim Avatar answered Sep 12 '25 19:09

Abdul Munim


A very simple approach:

var html = '<span>Remove <b>tags &amp; entities</b></span>';
var noTagText = $(html).text();
// ==> noTagText = 'Remove tags & entities'

Note that it will remove tags but also html entities.

like image 35
yolenoyer Avatar answered Sep 12 '25 18:09

yolenoyer