Javascript regex matching on a time - javascript

I want to see if the string I have is in the form of HH:MM:SS.
Here is what I have so far:
d = '00:01:01'
d.match(/\d{2}:\d{2}:\d{2}/)
["00:01:02"]
Is there a way to just get a True/False, instead of an array?

Use .test method of Regexp object.
/\d{2}:\d{2}:\d{2}/.test(d)
// true

Perhaps, you can use regex.test(str) but it's also possible using match because on success, match returns an array which is a truthy value and on failure, match returns null which is a falsy value. Check this to understand truthy and falsy.
So, if you use
if(d.match(/\d{2}:\d{2}:\d{2}/)) {
// true
}
else {
// false
}
This will work, check this fiddle as an example and this answer as well (about !!), I've used !! in my example, so you may have doubts.

Related

return true if only there is exact include

Using includes method we get true for all of these logs:
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('listen_again_long')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('listen_again')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('listen')); // true
But we know only the first log should return true because we have exactly listen_again_long inside the longer string.
if we consider this part fixed: https://example.com/test/media/instructions/
How we can only return true for the first one and false for the rest of the logs?
You are actually looking for a certain string enclosed in /, so one option would be to simply include both / in the argument you are passing to String.prototype.includes():
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('/listen_again_long/'));
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('/listen_again/'));
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('/listen/'));
You could also do the same thing using RegExps and RegExp.prototype.test():
console.log(/\/listen_again_long\//.test("https://example.com/test/media/instructions/listen_again_long/1.mp3"));
console.log(/\/listen_again\//.test("https://example.com/test/media/instructions/listen_again_long/2.mp3"));
console.log(/\/listen\//.test("https://example.com/test/media/instructions/listen_again_long/3.mp3"));
In both cases you could replace /listen_again_long/ with the whole thing if you want to make sure the match doesn't happen in a different place:
"...".includes("https://example.com/test/media/instructions/listen_again_long/");
Or, with RegExp:
/https:\/\/example.com\/test\/media\/instructions\/listen_again_long\//.test("...");
You'll have to extract the substring you want to compare against your parameter and then do a straight === comparison.
var url = <your passed in mp3 file>;
var s = "https://example.com/test/media/instructions/"
var substring = url.substring(url.indexOf(s) + url.length);
substring = substring.substring(0, url.indexOf("/");
substring === "listen_again_long"

What does an if (number) return?

I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..
In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.
The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.
It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.
It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead
if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}
length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

how can I fix this regular expression function?

This is the first part of my code in a function:
var pattern = new RegExp(myTypedString,"gi");
The goal is to populate results as I type in a text field. Everytime an input event is triggered I loop through an array of strings and check if my typed string exists in my array of strings using this code:
return pattern.test(myArrayString);
but luckily I've realised that one of the results was wrong and it was only happening to this particular case: when I type "t" or "T" I don't have a match in "Trafalgar Square" (a string from myArrayString), so I did a few debugging in the console and when I check the variable pattern doing console.log(pattern) it outputs this string: /t/gi, which i think it's where my problem relies... (later on this)
when I tried to replicate the problem typing:
var pattern = new RegExp('t',"gi")
and:
pattern.test('Trafalgar Square')
which gives me true at a first try, BUT... if I type this again:
pattern.test('Trafalgar Square')
the result will be false and if I continue, true, false, true, false,...
One of the first things that came into my mind is that the /t in the regex /t/gi might be a rule but I couldn't find anything about it.
I would like to know an explanation for this unexpected result but I'm also concerned that my function is not flawless, so I ask you how can I improve this function? thanks
It alternates between true and false because it matches the first time (true), then tries a second match, which fails because there’s only one T in Trafalgar Square. When you call it again, it loop back, thus the true, false, true, etc.
To fix that, update its cursor before matching:
var p = new Regexp('t', 'gi') // same as `p = /t/gi`
// ...
p.lastIndex = 0;
p.test("Trafalgar Square"); // true
// try again:
p.lastIndex = 0;
p.test("Trafalgar Square"); // true -> it works
Here is a relevant jsfiddle with a couple examples.
I do not know why it alternates between true and false (i can reproduce it, too). The /t/ should not be anything special in the regex. It is not a special character like { or \ or [ and should just be a literal character t.
But you could use another function to achieve more or less the same:
'Trafalgar Square'.match(pattern)
=> Array [ "T" ]
'lalala'.match(pattern)
=> null
match takes slightly more resources than test would, but this is usually not a problem. The result will be an Array for matches or null when nothing matches, so you can just return that and the rest of your code will probably work just fine. Array... will be a truthy value and null will be a falsy value.

string compare in javascript that returns a boolean

Is there a function in javascript that compares a string and returns a boolean? I found .match but it returns the strings that matched. I was hoping there was something else so that I would have a lesser code in comparing a string. Since I wanted to check if a string has this word and proceed else not.
thanks
You can use the RegEx test() method which returns a boolean:
/a/.test('abcd'); // returns true.
You may use type augmentation, especially if you need to use this function often:
String.prototype.isMatch = function(s){
return this.match(s)!==null
}
So you can use:
var myBool = "ali".isMatch("Ali");
General view is that use of type augmentation is discouraged only because of the fact that it can collide with other augmentations.
According to Javascript Patterns book, its use must be limited.
I personally think it is OK, as long as you use a good naming such as:
String.prototype.mycompany_isMatch = function(s){
return this.match(s)!==null
}
This will make it ugly but safe.
there is .indexOf() which will return the position of the string found, or -1 if not found
myString.indexOf(myWord) > -1
or, if you want a function:
function hasWord(myString, myWord) {
return myString.indexOf(myWord) > -1;
}
I know this isn't the exact answer you are looking for but this is always an effective way to do this.
if(var1 == var2){
//do this
}else{
//do that
};
Actually, .match()can do the trick for you because it returns an array of pattern matching strings if any, null otherwise.
Anyway, if you just want to check if a string contain another string you're more likely to use indexOf() (it will return -1 if no substring is found).
The first solution is a bit overkill for your purpose.
If on the other end you want to check for equality you can use `string1 === string2``
You can just use a compare.
if ("dog" == "cat") {
DoSomethingIfItIsTrue();
} else {
DoSomethingIfItIsFalse();
}
If anyone still has doubts ...
It was quoted by another colleague using the indexOf() method. The return of this method is either "-1", if it does not find the String in the Array, or the position of the case it finds.
To use it with the desired return, you would have to perform a check before, such as:
exampleMethod () {
const expression = ['string1', string2] .indexOf (this.exampleObject);
if (expression! = -1) {
return true;
} else return false;
}
Basically, you would take advantage of this return.
However, the includes() method can simply be used:
exampleMethode(): boolean {
return ['string1', 'string2'].includes(this.exampleObject);
}
The return of this method will do what you want in a simple way. Compares the object string with the string array you want to check, and returns a boolean.

Categories

Resources