Javascript compare case insensitive strings

I need to check some strings using JavaScript, but case sensitivity is causing problems. eg

if('abc'=='ABC') { return true; } 

it will not go inside the if loop, although the meaning of the word will be the same. I cannot use the tolower clause too, since I do not know how this will happen for ex:

 if('abc'=='ABC') { return true; } 

how to write a js function for this if it can be done using jquery.

+54
javascript jquery jquery-plugins
Feb 07 2018-11-11T00:
source share
4 answers

You can make both arguments lowercase, and this way you will always be case insensitive.

 var string1 = "aBc"; var string2 = "AbC"; if (string1.toLowerCase() === string2.toLowerCase()) { #stuff } 
+110
Feb 07 '11 at 8:52
source share

Another method using regex (this is more correct than Zachary's answer):

 var string1 = 'someText', string2 = 'SometexT', regex = new RegExp('^' + string1 + '$', 'i'); if (regex.test(string2)) { return true; } 

RegExp.test () will return true or false.

Also, by adding '^' (indicating the beginning of a line) to the beginning and '$' (indicating the end of a line) to the end, make sure your regular expression matches only if “sometext” is the only text in stringToTest. If you are looking for text that contains a regular expression, it is normal to leave them turned off.

It is just easier to use the string.toLowerCase () method.

So ... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don’t understand.

There are tons of regular 'tutorials' expressions, but most seem to be trying to push a specific product. Here, what looks like a decent tutorial ... provided, it's written to use php, but otherwise it looks like a good primer: http://weblogtoolscollection.com/regex/regex.php

This seems to be a good regexp tool: http://gskinner.com/RegExr/

+18
May 25 '12 at 14:44
source share

You can also use string.match ().

 var string1 = "aBc"; var match = string1.match(/AbC/i); if(match) { } 
+8
Feb 07 '11 at 9:00
source share

Try it...

 if(string1.toLowerCase() == string2.toLowerCase()){ return true; } 

Also, this is not a loop, it is a block of code. Loops are usually repeated (although they can only be executed once), while a block of code is never repeated.

I read your note that I am not using toLowerCase, but I can not understand why this will be a problem.

+4
Feb 07 2018-11-11T00:
source share



All Articles