Run action if contains part of an attr value - javascript

I have a input with this
attr('data-disabled-dates','12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022')
And a const which results in tomorrow dynamically, so for this case the result is "16/02/2022"
Now i want to run action if it matches that tomorrow's date is within the attr data-disabled-dates.
So i tried this
if (jQuery(input).attr('data-disabled-dates') == '16/02/2022')
{ console.log('work') } else {
console.log ('not') }
But it only gives me true if the whole sequence is exactly the same, that is, if I put "12/02/2022; 13/02/2022..." if it will give the result, but I only want it to be true if the value I am putting is inside

You can use String.includes() or String.split('; ') to convert string to array and check if it includes the desired value.
if (jQuery(input).attr('data-disabled-dates').includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
Working example in vanilla JS
const div = document.querySelector('#data');
const dates = div.getAttribute('data-disabled-dates');
if (dates.includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
// or
if (dates.split('; ').includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
<div id="data" data-disabled-dates="12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022" />
btw https://youmightnotneedjquery.com/

== performs exact string matches, not substring matches.
You can use .split() to split the attribute value into an array, then use .includes() to test if the array contains the date.
if (jQuery(input).data('disabled-dates').split('; ').includes('16/02/2022')) {
console.log("work");
} else {
console.log("not");
}

You can use indexOf to be greater than 0. IndexOf if you need to support IE.
var dataAttrValue = jQuery(input).attr('data-disabled-dates');
var date = '16/02/2022';
if (typeof dataAttrValue !== 'undefined' && dataAttrValue.indexOf(date)) > 0) { console.log('work');
} else {
console.log ('not');
}
OR
jQuery(input).is(“[data-disabled-dates*='16/02/2022']”);
But I suggest using JQuery Data to store and retrieve values from elements.

Related

Check if all values of array are equal to number

I want to see if there is a better way to check if all values of array are equal to number. I have it working with a foreach but wanted to see if I can do this anyway else?
let valid = true;
$.each(data.resultStatus, function (index, resultStatus) {
if (resultStatus.ResultCode == "2") {
valid = false;
}
});

How to find whole substring in string?

I have a string and I have to check if that string contains defined substring I need to do some work and otherwise, I should return some error.
I have the following code:
function isContains(myString) {
let subString = 'test1234';
if(myString.includes(subString)) {
// to do some work
} else {
// return some error.
}
}
but the problem is if myString = 'my-string-test1-rrr' its condition return true.
How can I get true only in case when the whole subString was included in myString?
Use indexOf() instead.
function isContains(myString) {
let subString = 'test1234';
if(myString.indexOf(subString) > -1) {
// to do some work
} else {
// return some error.
}
}
you can use regex to check if that value is present are not;
example 1
without containing the specific string
var test = 'my-string-test1-rrr';
console.log(' test --- ', test.match(/test1234/g))
example 2
contains the specific string
var test = 'my-string-test1234-rrr';
console.log(' test --- ', test.match(/test1234/g))
It is highly recommended to use includes() over indexOf() and further indexOf returns the index of the occurrence where you would prefer an immediate answer - false / true if that substring is found inside the searched string.
Your function does exactly what you are asking. I would suggest to isolate the retrieval of this function and make it purer like so, then when you have the return boolean value you could utilize it after to run whatever logic you wish. This way you keep this function pure and separate your concerns better.
I also believe it would be easier for you to debug your issue if you isolate this functions like In the example I provided.
function isContains(myString) {
let subString = 'test1234';
let isContains = false;
if(myString.includes(subString)) {
isContains = true;
} else {
isContains = false;
}
return isContains;
}
You could use it like so in a later phase in your code:
const myString = 'my-string-test1-rrr';
let shouldRunOtherLogic = isContains(myString);
if (shouldRunOtherLogic) {
// to do some work
} else {
// return some error.
}
Hope I could help, if there's anything further you may need feel free to let me know.

Check if string is starting with prefix

I would like to check with javascript if array items starts with the word "prefix".
So far I've done something like this:
let array = ["prefix-word1", "prefix-word2"];
array.forEach(function(element) {
if (element.lastIndexOf('prefix', 0) == 0) {
console.log('prefix');
}
}
For some reason I keep get an error that prefix is not defined. Please help.
This one works (check the comments on the code):
let array = ["prefix-word1", "prefix-word2" , "does not start with prefix"];
array.forEach(function(element) {
// Check if the first word is prefix
if (element.indexOf('prefix') == 0) {
console.log('prefix');
console.log(element);
}
});
console.log("Second approach which is not suggested");
array.forEach(function(element) {
// not the correct approach as suggested by #Barmar though it works
if (element.lastIndexOf('prefix',0) == 0) {
console.log('prefix');
console.log(element);
}
});
Try using double quotation marks instead of single like this "prefix" in functions.

json array check if there does not need to insert in localstorage?

I need to check a JavaScript array to see if there are duplicate values ​​. What is the easiest way to do this ? I just need to check whether the values ​​already exist if there is not need to go into json array.
function cek() {
resi_or_code = document.getElementById('code_or_resi').value;
resi = resi_or_code.split(',');
if($.trim(resi_or_code) != ''){
location.href = base_url + 'resi/' + encodeURIComponent(resi_or_code);
}
if (localStorage.daftar_data){
daftar_data = JSON.parse(localStorage.getItem('daftar_data'));
$("#riwayat").toggle();
}
else {
daftar_data = [];
}
for (y in daftar_data){
var q = daftar_data[y].resis;
for (x in resi){
console.log(q);
if (q === resi[x])
{
console.log('Value exist');
}else{
console.log('Value does not exist');
daftar_data.push({'resis':resi[x]});
localStorage.setItem('daftar_data', JSON.stringify(daftar_data));
}
}
}
}
If i understand your question and code right, you basically have an array of objects where each object has key resis
If that is the case, below code might help
var valueArray = ar.map(function(item) {
return item.resis;
})
// To check for duplicate
if(valueArray.indexOf(value) !== -1) {
// Duplicates
} else {
// No duplicate
}
In your case,
ar would be daftar_data.
I am really not sure what your value is. is it resi?
Basically, you should try replacing your for loop with the above code.
By far the simplest way is to simply sort your array using Array.sort(). This will perform well and reduces you duplicate check to a simple for-loop that compares each value with its neighbor.
Solutions that attempt to avoid sorting will almost certainly scale very badly.
So to recap and show some code:
daftar_data.sort();
for (var index = 0; index < daftar_data.length - 1; index++)
{
if (daftar_data[index] === daftar_data[index+1]) {
// Found a duplicate
}
}
If the natural sort order of the objects don't work for you, supply a function to the sort function, like so:
daftar_data.sort(function(a, b) {
// return any value > 0 if a is greater, < 0 if b is greater
// and 0 if they are equal.
});
Note that in this form, you can actually check for the duplicate in your compare function.

slice different arrays and return selected values

I am working on a problem. I do not know the right question to ask in order to solve this problem. I have gotten what seems to be the required results but the verification problem for the solution does not work. I am not sure if I am solving it correctly. Basically I am given an array and I have to filter out elements from that array by slicing certain ingredients.
question: "We only use the elements that the instruction tells us to. So, we need to create a slice of the given array of elements (taken from the beginning) to resemble only the elements we are using. If the instruction doesn't say anything, we only take the first element."
var hammerIngredients = ['iron', 'granite', 'copper'];
var spearIngredients = ['iron', 'granite', 'copper'];
var panIngredients = ['iron', 'granite', 'copper'];
take(hammerIngredients); // returns ['iron']
take(spearIngredients, 2); // returns ['iron', 'granite']
take(panIngredients, 3); // return ['iron', 'granite', 'copper']
"If the instruction says to use more than the elements listed, we use all the elements in the array. If the instruction says to use no elements, we return an empty array."
var plateIngredients = ['iron', 'granite', 'copper'];
take(plateIngredients, 0); // returns []
So I have tried to do the program and I have done the following. It appears to work, but when I try to verify it I get that it is invalid.
function take(ingredients, slicer) {
if (arguments.length === 1) {
slicer = 1;
}
if (ingredients === hammerIngredients){
return ingredients.slice(0, slicer);
} else if(ingredients === spearIngredients) {
return ingredients.slice(0,slicer);
} else if (ingredients === panIngredients) {
return ingredients.slice(0,slicer);
} else if (ingredients === plateIngredients) {
return ingredients.slice(0,slicer)
} else {
return;
}
}
And I have no idea why. Help please!
you have no logic for if the slicer parameter is 0, in which case you need to return an empty array.
Put this line in there and it should work, based on the requirements you gave:
if (slicer === 0) {
return [];
}
You code currently only works if one of those three exact arrays are used. Does the verification code create and use only those arrays?
Your code does not need to be tied to existing ingredient arrays. After setting the default slicer value you can just:
return ingredients.slice(0,slicer);

Categories

Resources