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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With