简体   繁体   中英

How to match a part of a string with array values using jquery / javascript

I have a javascript array:

var exclude = ["Santorum","Obama","Romney","Gingrich"];

I have html links:

<a href="" class="title">Santorum is seeking campaign funding</a>
<a href="" class="title">Clinton is stepping down as Secretary</a>
<a href="" class="title">Obama is seeking reelection</a>

I want to check whether any of the a-links have any one of the exclude-values in them, and if they do, then remove them. So the result would be:

<a href="" class="title">Clinton is stepping down as Secretary</a>

The other two would be removed as they possess words from the array. I've tried using jQuery.inArray but I can't seem to figure it out. Thx for your help.

Something like:

var exclude = ["Santorum","Obama","Romney","Gingrich"];

$('a.title').filter($.map(exclude, function (val) {
    return ':contains("' + val + '")';
}).join()).remove();

http://jsfiddle.net/SxP2a/

Try looping though the excluded words, and remove links that have them.

For example (using the :contains selector ):

$.each(exclude, function(i, v){
    $('a.title:contains("'+v+'")').remove();
});

DEMO: http://jsfiddle.net/H6FPb/

EDIT: You said the <a> is wrapped in a <div> , then you can do:

$.each(exclude, function(i, v){
    $('a.title:contains("'+v+'")').parent('div').remove();
});

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