Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string compare in javascript that returns a boolean

Tags:

javascript

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

like image 700
magicianiam Avatar asked May 22 '12 15:05

magicianiam


2 Answers

You can use the RegEx test() method which returns a boolean:

/a/.test('abcd'); // returns true.
like image 144
Noah Freitas Avatar answered Sep 24 '22 14:09

Noah Freitas


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.

like image 31
Aliostad Avatar answered Sep 22 '22 14:09

Aliostad