How to check the word in an array
I have a default array for example
a=["and","a","in","&"] etc...
Iam getting a dynamic text, which iam converting it into an array. for example.
b=["harry","in","co开发者_如何学编程nnect"]
I need to highlight by avoiding "in" the array.
So harry and connect will be highlight but not the in?
How to compare or check the array in jquery?
you can use $.inArray
or $.grep
, i.e.
var a=["and","a","in","&"];
var b=["harry","in","connect"];
var c = $.grep(b, function(n){
return $.inArray(n,a) == -1;
});
This will return a new array, containing only the words NOT present in array a
Here's a fiddle: http://jsfiddle.net/kaFvw/
If you need it to return an array with all the words PRESENT in array a
, just change the ==
operator to !=
$.each(b, function(c,d) {
if (d == "in") //do not highlight
});
You can use jquery.each.
jQuery.each(b, function() {
// 'this' will hold value . you can do your operation here
if(this!="in")
{
//heighlight
}
});
You can find more details Here
do something like this;
a=["and","a","in","&"]
b=["harry","in","connect"]
var foo;
$.each(b, function() {
if(Query.inArray(this, a)!=-1)
{
foo += "<strong>" + this + "</strong>";
}
else{
foo += this;
}
});
If I understood correctly, you want to highlight all the elements in the second array that are not contained by the first one. If that's the case, then something like this should work :
for(var i=0,l=b.length;i<l;i++)
{
if(a.indexOf(b[i]) == -1)
{
// highlight b[i]
}
else
{
// do no highlight b[i]
}
}
精彩评论