Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...