js compare string case insensitive code example

Example 1: Javascript case insensitive string comparison

var name1 = "Taylor Johnson";
var name2 ="taylor johnson";

//convert to lowercase for case insensitive comparison
if(name1.toLowerCase() === name2.toLowerCase()){
    //names are the same
}

Example 2: how to compare strings in javascript ignoring case sensitive

const str1 = '[email protected]';
const str2 = '[email protected]';

str1 === str2; // false
str1.toLowerCase() === str2.toLowerCase(); // true

Example 3: compare string camelcase and lowercase javascript

function sameCase(str) {
  return /^[A-Z]+$/.test(str) || /^[a-z]+$/.test(str);
}

Example 4: javascript string insensitive compare

const str1 = '[email protected]';
const str2 = '[email protected]';

str1 === str2; // false

// will return 0, means these two strings are equal according to `localeCompare()`
str1.localeCompare(str2, undefined, { sensitivity: 'accent' });

Example 5: compare string camelcase and lowercase javascript

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
    // Your code here
}