I'm putting together a search function that searches through multiple data attributes on a lot of divs on a page. Below is the code I have working for this. My problem I've come across is that it only seems to search the first word each data attribute except the last one.
var filter = $(this).val();
var regExPattern = "gi";
var regEx = new RegExp(filter, regExPattern);
$(".box").each(function(){
if (
$(this).data('attr1').search(regEx) &&
$(this).data('attr2').search(regEx) &&
$(this).data('attr3').search(regEx) &&
$(this).data('attr4').search(regEx) < 0
)
{
//Do Something
}
else
{
//Do Something else
}
});
I've put together a fiddle that replicates this problem here.
I've tried different combinations of searching... such as putting all the data attributes into an array and then searching elements one by one, but that takes along time to complete.
I would be much appreciated if anyone can help with this?
Your condition is confusing. .search() returns the index of a match or -1. So it yields a falsy value (0) only when the regex is found at the start of the string, and a truthy number otherwise. So change it to
$(this).data('attr1').search(regEx) < 0 &&
$(this).data('attr2').search(regEx) < 0 &&
$(this).data('attr3').search(regEx) < 0 &&
$(this).data('attr4').search(regEx) < 0
Or, since you don't need the position, switch to regEx.test()
Related
solved: requires explicit return statement for each filter. I thought the single boolean in each filter would be clear enough. by #adiga
I want to find the elements in one array (dcm) that are not found in a second array (vari). I want to match only two elements, vp (string type) and vd (date type). I've made sure there are some rows in dcm that meet the condition, but I'm getting no results.
Did I do up the code wrong? is there a better way to do this (.includes .contains .indexOf)?
var dcmm = dcm.filter(r=>{
vari.filter(rv=>{
rv[vp]+rv[vd] == r[dp]+r[dd]
}).length == 0
});
ps. sorrynotsorry to all the long variable name proponents out there. as well as the const-not-var proponents.
pps. this is google apps script not javascript, but I think the idea is the same.
Just in case, as it said #adiga you don't need return statements if you don't use {}.
Most likely this will work fine:
var dcmm = dcm.filter( r => vari.filter( rv => (rv[vp]+rv[vd] == r[dp]+r[dd]) ).length == 0 );
Using JavaScript, I'm going through an array of objects. If the object has 1 or more values that are not null or empty, a <p> element is created and then appended to the container element.
var tempElem = document.createElement("P");
if( item.valueOne !== '' )
tempElem.innerHTML += item.valueOne;
if( item.valueTwo !== '' )
tempElem.innerHTML += item.valueTwo;
if( tempElem.innerHTML !== '' )
containerElem.appendChild(tempElem);
The above does filter out most empty entries, however a few are somehow making it through to the page.
On chrome, it shows exactly <p></p>
I've done some analyzing, and before the last if-statement...
typeof tempElem.innerHTML = string
tempElem.innerHTML.length = 4
tempElem.innerHTML.charCodeAt(0) = 1
tempElem.innerHTML.charCodeAt(1) = 1
tempElem.innerHTML.charCodeAt(2) = 1
tempElem.innerHTML.charCodeAt(3) = 1
tempElem.innerHTML.charCodeAt(4) = NaN
I'm quite lost on this one. The actual data is in json and for these particular values, I'm seeing key:"". Which is exactly the same as the ones that are being filtered just fine.
I know I can check the values in javascript before creating any kind of dom element, but I'd like to know what's causing this and how to fix it directly.
Turns out it was due to my usage of the .trim() method.
STRING.trim() does not remove characters such as x00 (Start of Header), x01 (Start of Text), etc.
If present in an otherwise empty string however, these characters will still pass a ==="" check.
For my specific purposes, this simple regex fixes the issue:
str.match(/[^\x00-\x20\x7F]/)
(will return true if at least 1 non space or 'empty' character exists)
I have an array that looks like this:
var coll = [
{
prop1:true,
prop2:false,
id:"888399"
},
{
prop1:true,
prop2:true,
id:"/XS-555224"
},
{
prop1:false,
prop2:false,
id:"/DL-555444"
}
]
I want to sort the array so that the element with the ID that begins with "/DL" (for which there will always only be one) always starts at the top. How do I do that?
I don't feel like a custom sort will be the best choice because I don't have to compare elements against one another, I only have to find the one with the "/DL", slice it out, and insert it at the beginning of the array.
However, to do that, I'll still need to iterate over each element of the array to find the element and then perform a couple operations. So then I start thinking that I might as well just do the sort. The problem is how to write the correct condition to compare 2 items and checking the beginning of the ID string. So I figure that I can just simply test for the beginning of the String and return the value myself without comparison.
So I try this:
coll.sort(function(a,b){
var itemA = a.id;
var itemB = b.id;
if(itemA.lastIndexOf("/DL") === 0){
return 1;
}
});
But this comparison isn't working. What is wrong with my custom compare function? Thanks for any helpful tips.
Even though you are just looking for one record to move to the front you still need to check both parameters in the sort, it could be either one.
coll.sort(function(a,b) {
return a.id.indexOf('/DL') === 0 ? -1 : b.id.indexOf('/DL') === 0 ? 1 : 0;
});
Basically we want the '/DL' record to be the 'lowest' value in the array so it will show up first (sort orders things low to high). If a is lower we return negative, if b is lower we return positive. So when sorting if a is the /DL we need to return a negative. If b is the /DL we return a positive. So this expression in english is basically "Is a is our record? -1. If not, is b our record? 1. If neither then 0."
you can try this:
var orderedArr = coll.sort(function(val){
return !val.id.toString().startsWith('/DL');
});
[EDIT]
Once that you have user with IE, you can add this to make your life easier in the future:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
so you'll be able to use startsWith now and whenever you want.
I'm trying to display only the odds from bet365 from a javacript piece of code. I can only think of doing this by searching for a part of the id of the bet, each bookie has its own related ids and bet365's is b3, so this query below I've tried to search for ids where the string includes the "b3" in it, as all other parts of it seem completely random
http://www.oddschecker.com/horse-racing/2015-06-30-chepstow/18:10/winner
var odds = document.getElementsByTagName("odds");
for (var i = 0; i < odds.length; i++) {
if(odds[i].id.indexOf("b3") == 0) {
odds[i].disabled = bDisabled;
}
}
Whenever I do this my return says undefined. How can I get this to work
It looks like the marker you're looking for is .co, from what I can see from the code (delimiting a td with the odds as inner content).
The site also has jQuery loaded up, so let's use jQuery to simplify the pseudo-code (we can always transform it to pure javascript later):
var odds = $('.co');
odds.each(function(){
var id = $(this).attr('id');
if(id.indexOf('_B3') >= 0){
console.log(id);
//your code here
}
});
Given that the ID is not at the end of the ID string, we can't check to see if the indexOf is == to 0; instead, we just want to know if the ID we're looking for (b3) is contained in that string. So we're looking for any value that is not -1, the value returned by indexOf when the query is not found in the original string.
I'm searching for specifically for _B3 for two reasons: One, indexOf is case sensitive, so given that your ID are uppercase, we must make our search uppercase too. I'm also adding the underscore in order to respect the ID string format, as I'm not 100% certain that your ID will only contain letters to delimit IDs from the bet vendor, so we can't be too safe with that.
In pure javascript:
var odds = document.getElementsByClassName('co');
for(var ii = 0; ii < odds.length; ii++){
if(odds[ii].id.indexOf("_B3") >= 0){
console.log(odds[ii].id);
//your code here
}
}
I got 2 variables;
value = 'com';
longString= "com-233-123-232-123";
I'd like to check if "value" is inside "longString". I tried using regex with test() but I fail, maybe you know better.
I think the indexOf(substr, [start]) is enough no need to regex.
indexOf(substr, [start])
Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search. Default is 0.
http://www.javascriptkit.com/javatutors/string4.shtml
Two ways
1st indexOf
if (longString.indexOf(value) != -1)
// found
else
// not found
2nd split
var value = 'com'; var longString= "com-233-123-232-123";
var split1=longString.split("-");
var i=0;
var found=0;
while (i<split1.length)
{
if(split1[i]==value)
{
found=1;
break;
}
i++;
}
if(found==1)
//found
else
//not found
Don't use regular expressions for this - if the value you're looking for can be interpreted as a regular expression itself then you'll have trouble. Just check for longString.indexOf(value) != -1.
What does jQuery has to do with this? This is a simple Javascript problem
if (longString.indexOf(value) != -1)
// We found it
else
// We didn't find it