Reputation: 1579
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
Upvotes: 9
Views: 33267
Reputation: 1
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.
Upvotes: 0
Reputation: 11
You can just use a compare.
if ("dog" == "cat") {
DoSomethingIfItIsTrue();
} else {
DoSomethingIfItIsFalse();
}
Upvotes: 0
Reputation: 81660
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.
Upvotes: 14
Reputation: 2977
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``
Upvotes: 0
Reputation: 17430
You can use the RegEx test()
method which returns a boolean:
/a/.test('abcd'); // returns true.
Upvotes: 32
Reputation: 5757
myString.indexOf(myWord) > -1
or, if you want a function:
function hasWord(myString, myWord) {
return myString.indexOf(myWord) > -1;
}
Upvotes: 1
Reputation: 9939
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
};
Upvotes: 0
Reputation: 32532
there is .indexOf()
which will return the position of the string found, or -1 if not found
Upvotes: 5