String comparison in javascript returning a boolean

Is there a function in javascript that compares a string and returns a boolean? I found .match, but it returns strings that match. I was hoping there was something else so that I had less code when comparing a string. Since I wanted to check if the string has this word, and do not do another.

thanks

+6
source share
7 answers

You can use the augmentation type, 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"); 

The general view is that the use of a type extension is not recommended just because it may interfere with other add-ons.

According to Javascript Patterns , its use should be limited.

I personally think that everything is fine if you use a good name, for example:

 String.prototype.mycompany_isMatch = function(s){ return this.match(s)!==null } 

This will make it ugly but safe .

+11
source

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

 /a/.test('abcd'); // returns true. 
+9
source

there is .indexOf() that will return the position of the found string, or -1 if not found

+5
source
 myString.indexOf(myWord) > -1 

or if you want to use the function:

 function hasWord(myString, myWord) { return myString.indexOf(myWord) > -1; } 
+1
source

You can just compare.

 if ("dog" == "cat") { DoSomethingIfItIsTrue(); } else { DoSomethingIfItIsFalse(); } 
0
source

I know that this is not the exact answer you are looking for, but it is always an effective way to do this.

 if(var1 == var2){ //do this }else{ //do that }; 
0
source

Actually, .match() can do the trick for you, because it returns an array of strings matching the pattern, if any, but otherwise.

In any case, if you just want to check if the string contains another string, you are more likely to use indexOf() (it will return -1 if the substring is not 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``

0
source

Source: https://habr.com/ru/post/916363/


All Articles