Determining the case (upper/lower) of the first letter in a string - javascript

In a web application, how do I determine whether the first letter in a given string is upper- or lower-case using JavaScript?

You can use toUpperCase:
if(yourString.charAt(0) === yourString.charAt(0).toUpperCase()) {
//Uppercase!
}
If you're going to be using this on a regular basis, I would suggest putting it in a function on the String prototype, something like this:
String.prototype.isFirstCapital = function() {
return this.charAt(0) === this.charAt(0).toUpperCase();
}
if(yourString.isFirstCapital()) {
//Uppercase!
}
Update (based on comments)
I don't know what you actually want to do in the case that the string does not being with a letter, but a simple solution would be to add a quick check to see if it does or not, and return false if not:
String.prototype.isFirstCapital = function() {
return /^[a-z]/i.test(this) && this.charAt(0) === this.charAt(0).toUpperCase();
}

This will work only with English alphabet.
var ch = myStr.chatAt(0);
if (ch >= 'a' && ch <= 'z') {
// small
} else if (ch >= 'A' && ch <= 'Z') {
// capital
} else {
// not english alphabet char
}

var mystring = "Test string";
var first= "";
if (mystring )
{
first= mystring[1];
}
if (first)
{
$('p').each(function()
{
if ($(this).text().charAt(0).toUpperCase() === $(this).text().charAt(0))
{
alert("Uppercase");
}
});
}

This will be called recursively until a first letter in a string is approached, otherwise returns 'no letters'.
function getFirstCase(string) {
if (string === '') return 'no letters';
var firstChar = string.charAt(0);
/*
* If both lowercase and uppercase
* are equal, it is not a letter
*/
if (firstChar.toLowerCase() === firstChar.toUpperCase()) {
return getFirstCase(string.substr(1));
} else {
return firstChar.toLowerCase() === firstChar ? 'lowercase' : 'uppercase';
}
}
Testing:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));

I'm surprised no one's offered a regex solution to this - it seems like the easiest by far:
function getFirstCase(s) {
return (/^[\d\W]*[A-Z]/).test(s) ? 'upper' :
(/^[\d\W]*[a-z]/).test(s) ? 'lower' :
'none';
}
Blatantly stealing #Lapple's test cases:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
// lower upper none upper upper
See http://jsfiddle.net/nrabinowitz/a5cQa/

Related

checking for palindromes in js [duplicate]

I have the following:
function checkPalindrom(palindrom)
{
for( var i = palindrom.length; i > 0; i-- )
{
if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
{
document.write('the word is palindrome.');
}else{
document.write('the word is not palindrome!');
}
}
}
checkPalindrom('wordthatwillbechecked');
What is wrong with my code? I want to check if the word is a palindrome.
Maybe I will suggest alternative solution:
function checkPalindrom (str) {
return str == str.split('').reverse().join('');
}
UPD. Keep in mind however that this is pretty much "cheating" approach, a demonstration of smart usage of language features, but not the most practical algorithm (time O(n), space O(n)). For real life application or coding interview you should definitely use loop solution. The one posted by Jason Sebring in this thread is both simple and efficient (time O(n), space O(1)).
25x faster than the standard answer
function isPalindrome(s,i) {
return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}
use like:
isPalindrome('racecar');
as it defines "i" itself
Fiddle: http://jsfiddle.net/namcx0yf/9/
This is ~25 times faster than the standard answer below.
function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
Fiddle: http://jsfiddle.net/t0zfjfab/2/
View console for performance results.
Although the solution is difficult to read and maintain, I would recommend understanding it to demonstrate non-branching with recursion and bit shifting to impress your next interviewer.
explained
The || and && are used for control flow like "if" "else". If something left of || is true, it just exits with true. If something is false left of || it must continue. If something left of && is false, it exits as false, if something left of a && is true, it must continue. This is considered "non-branching" as it does not need if-else interupts, rather its just evaluated.
1. Used an initializer not requiring "i" to be defined as an argument. Assigns "i" to itself if defined, otherwise initialize to 0. Always is false so next OR condition is always evaluated.
(i = i || 0) < 0
2. Checks if "i" went half way but skips checking middle odd char. Bit shifted here is like division by 2 but to lowest even neighbor division by 2 result. If true then assumes palindrome since its already done. If false evaluates next OR condition.
i >= s.length >> 1
3. Compares from beginning char and end char according to "i" eventually to meet as neighbors or neighbor to middle char. If false exits and assumes NOT palindrome. If true continues on to next AND condition.
s[i] == s[s.length-1-i]
4. Calls itself again for recursion passing the original string as "s". Since "i" is defined for sure at this point, it is pre-incremented to continue checking the string's position. Returns boolean value indicating if palindrome.
isPalindrome(s,++i)
BUT...
A simple for loop is still about twice as fast as my fancy answer (aka KISS principle)
function fastestIsPalindrome(str) {
var len = Math.floor(str.length / 2);
for (var i = 0; i < len; i++)
if (str[i] !== str[str.length - i - 1])
return false;
return true;
}
http://jsfiddle.net/6L953awz/1/
The logic here is not quite correct, you need to check every letter to determine if the word is a palindrome. Currently, you print multiple times. What about doing something like:
function checkPalindrome(word) {
var l = word.length;
for (var i = 0; i < l / 2; i++) {
if (word.charAt(i) !== word.charAt(l - 1 - i)) {
return false;
}
}
return true;
}
if (checkPalindrome("1122332211")) {
document.write("The word is a palindrome");
} else {
document.write("The word is NOT a palindrome");
}
Which should print that it IS indeed a palindrome.
First problem
= is assign
== is compare
Second problem, Your logic here is wrong
palindrom.charAt(palindrom.length)-1
You are subtracting one from the charAt and not the length.
Third problem, it still will be wrong since you are not reducing the length by i.
It works to me
function palindrome(str) {
/* remove special characters, spaces and make lowercase*/
var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if str is a Palindrome*/
return (removeChar === checkPalindrome);
}
As a much clearer recursive function: http://jsfiddle.net/dmz2x117/
function isPalindrome(letters) {
var characters = letters.split(''),
firstLetter = characters.shift(),
lastLetter = characters.pop();
if (firstLetter !== lastLetter) {
return false;
}
if (characters.length < 2) {
return true;
}
return isPalindrome(characters.join(''));
}
SHORTEST CODE (31 chars)(ES6):
p=s=>s==[...s].reverse().join``
p('racecar'); //true
Keep in mind short code isn't necessarily the best. Readability and efficiency can matter more.
At least three things:
You are trying to test for equality with =, which is used for setting. You need to test with == or ===. (Probably the latter, if you don't have a reason for the former.)
You are reporting results after checking each character. But you don't know the results until you've checked enough characters.
You double-check each character-pair, as you really only need to check if, say first === last and not also if last === first.
function checkPalindrom(palindrom)
{
var flag = true;
var j = 0;
for( var i = palindrom.length-1; i > palindrom.length / 2; i-- )
{
if( palindrom[i] != palindrom[j] )
{
flag = false;
break; // why this? It'll exit the loop at once when there is a mismatch.
}
j++;
}
if( flag ) {
document.write('the word is palindrome.');
}
else {
document.write('the word is not palindrome.');
}
}
checkPalindrom('wordthatwillbechecked');
Why am I printing the result outside the loop? Otherwise, for each match in the word, it'll print "is or is not pallindrome" rather than checking the whole word.
EDIT: Updated with changes and a fix suggested by Basemm.
I've added some more to the above functions, to check strings like, "Go hang a salami, I'm a lasagna hog".
function checkPalindrom(str) {
var str = str.replace(/[^a-zA-Z0-9]+/gi, '').toLowerCase();
return str == str.split('').reverse().join('');
}
Thanks
The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.
Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.
isPalindrome():
Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.
for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.
Here's the code:
/**
* TODO: If func counts out, let it return 0
* * Assume !isPalindrome (invert logic)
*/
function isPalindrome(S){
var s = S
, len = s.length
, mid = len/2;
, i = 0, j = len-1;
while(i<mid){
var l = s.charAt(i);
while(j>=mid){
var r = s.charAt(j);
if(l === r){
console.log('#while *', i, l, '...', j, r);
--j;
break;
}
console.log('#while !', i, l, '...', j, r);
return 0;
}
++i;
}
return 1;
}
var nooe = solution('neveroddoreven'); // even char length
var kayak = solution('kayak'); // odd char length
var kayaks = solution('kayaks');
console.log('#isPalindrome', nooe, kayak, kayaks);
Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.
function palindromCheck(str) {
var palinArr, i,
palindrom = [],
palinArr = str.split(/[\s!.?,;:'"-()]/ig);
for (i = 0; i < palinArr.length; i++) {
if (palinArr[i].toLowerCase() === palinArr[i].split('').reverse().join('').toLowerCase() &&
palinArr[i] !== '') {
palindrom.push(palinArr[i]);
}
}
return palindrom.join(', ');
}
console.log(palindromCheck('There is a man, his name! was Bob.')); //a, Bob
Finds and upper to lower case. Split string into array, I don't know why a few white spaces remain, but I wanted to catch and single letters.
= in palindrom[i] = palindrom.charAt(palindrom.length)-1 should be == or ===
palindrom.charAt(palindrom.length)-1 should be palindrom.charAt(palindrom.length - i)
Sharing my fast variant which also support spaces
function isPalindrom(str) {
var ia = 0;
var ib = str.length - 1;
do {
if (str[ia] === str[ib]) continue;
// if spaces skip & retry
if (str[ia] === ' ' && ib++) continue;
if (str[ib] === ' ' && ia--) continue;
return false;
} while (++ia < --ib);
return true;
}
var palindrom="never odd or even";
var res = isPalindrom(palindrom);
document.getElementById('check').innerHTML ='"'+ palindrom + '"'+" checked to be :" +res;
<span id="check" />
Some above short anwsers is good, but it's not easy for understand, I suggest one more way:
function checkPalindrome(inputString) {
if(inputString.length == 1){
return true;
}else{
var i = 0;
var j = inputString.length -1;
while(i < j){
if(inputString[i] != inputString[j]){
return false;
}
i++;
j--;
}
}
return true;
}
I compare each character, i start form left, j start from right, until their index is not valid (i<j).
It's also working in any languages
One more solution with ES6
isPalin = str => [...str].every((c, i) => c === str[str.length-1-i]);
You can try the following
function checkPalindrom (str) {
str = str.toLowerCase();
return str == str.split('').reverse().join('');
}
if(checkPalindrom('Racecar')) {
console.log('Palindrome');
} else {
console.log('Not Palindrome');
}
function checkPalindrom(palindrom)
{
palindrom= palindrom.toLowerCase();
var flag = true;
var j;
j = (palindrom.length) -1 ;
//console.log(j);
var cnt = j / 2;
//console.log(cnt);
for( i = 0; i < cnt+1 ; i++,j-- )
{
console.log("J is => "+j);
console.log(palindrom[i] + "<==>" + palindrom[j]);
if( palindrom[i] != palindrom[j] )
{
flag = false;
break;
}
}
if( flag ) {
console.log('the word is palindrome.');
}
else {
console.log('the word is not palindrome.');
}
}
checkPalindrom('Avid diva');
I'm wondering why nobody suggested this:
ES6:
// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
isPalindrom = (str = "") => {
if (str[0] === str[str.length - 1]) {
return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
}
return false;
}
alert(["aba", "acb", "aa", "abba", "s"].map((e, i) => isPalindrom(e)).join())
ES5:
// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
function isPalindrom(str) => {
var str = typeof str !== "string" ? "" : str;
if (str[0] === str[str.length - 1]) {
return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
}
return false;
}
alert(["aba", "acb", "aa", "abba", "s"].map(function (e, i) {
return isPalindrom(e);
}).join());
Recursive Method:
var low;
var high;
var A = "abcdcba";
function palindrome(A , low, high){
A = A.split('');
if((low > high) || (low == high)){
return true;
}
if(A[low] === A[high]){
A = A.join('');
low = low + 1;
high = high - 1;
return palindrome(A , low, high);
}
else{
return "not a palindrome";
}
}
palindrome(A, 0, A.length-1);
I thought I'd share my own solution:
function palindrome(string){
var reverseString = '';
for(var k in string){
reverseString += string[(string.length - k) - 1];
}
if(string === reverseString){
console.log('Hey there palindrome');
}else{
console.log('You are not a palindrome');
}
}
palindrome('ana');
Hope will help someone.
I found this on an interview site:
Write an efficient function that checks whether any permutation of an
input string is a palindrome. You can ignore punctuation, we only care
about the characters.
Playing around with it I came up with this ugly piece of code :)
function checkIfPalindrome(text) {
var found = {};
var foundOne = 0;
text = text.replace(/[^a-z0-9]/gi, '').toLowerCase();
for (var i = 0; i < text.length; i++) {
if (found[text[i]]) {
found[text[i]]++;
} else {
found[text[i]] = 1;
}
}
for (var x in found) {
if (found[x] === 1) {
foundOne++;
if (foundOne > 1) {
return false;
}
}
}
for (var x in found) {
if (found[x] > 2 && found[x] % 2 && foundOne) {
return false;
}
}
return true;
}
Just leaving it here for posterity.
How about this, using a simple flag
function checkPalindrom(str){
var flag = true;
for( var i = 0; i <= str.length-1; i++){
if( str[i] !== str[str.length - i-1]){
flag = false;
}
}
if(flag == false){
console.log('the word is not a palindrome!');
}
else{
console.log('the word is a palindrome!');
}
}
checkPalindrom('abcdcba');
(JavaScript) Using regexp, this checks for alphanumeric palindrome and disregards space and punctuation.
function palindrome(str) {
str = str.match(/[A-Za-z0-9]/gi).join("").toLowerCase();
// (/[A-Za-z0-9]/gi) above makes str alphanumeric
for(var i = 0; i < Math.floor(str.length/2); i++) { //only need to run for half the string length
if(str.charAt(i) !== str.charAt(str.length-i-1)) { // uses !== to compare characters one-by-one from the beginning and end
return "Try again.";
}
}
return "Palindrome!";
}
palindrome("A man, a plan, a canal. Panama.");
//palindrome("4_2 (: /-\ :) 2-4"); // This solution would also work on something like this.
`
function checkPalindrome (str) {
var str = str.toLowerCase();
var original = str.split(' ').join('');
var reversed = original.split(' ').reverse().join('');
return (original === reversed);
}
`
This avoids regex while also dealing with strings that have spaces and uppercase...
function isPalindrome(str) {
str = str.split("");
var str2 = str.filter(function(x){
if(x !== ' ' && x !== ',') {
return x;
}
});
return console.log(str2.join('').toLowerCase()) == console.log(str2.reverse().join('').toLowerCase());
};
isPalindrome("A car, a man, a maraca"); //true
function myPolidrome(polidrome){
var string=polidrome.split('').join(',');
for(var i=0;i<string.length;i++){
if(string.length==1){
console.log("is polidrome");
}else if(string[i]!=string.charAt(string.length-1)){
console.log("is not polidrome");
break;
}else{
return myPolidrome(polidrome.substring(1,polidrome.length-1));
}
}
}
myPolidrome("asasdsdsa");
Thought I will share my solution using Array.prototype.filter(). filter()
filters the array based on boolean values the function returns.
var inputArray=["","a","ab","aba","abab","ababa"]
var outputArray=inputArray.filter(function isPalindrome(x){
if (x.length<2) return true;
var y=x.split("").reverse().join("");
return x==y;
})
console.log(outputArray);
This worked for me.
var number = 8008
number = number + "";
numberreverse = number.split("").reverse().join('');
console.log ("The number if reversed is: " +numberreverse);
if (number == numberreverse)
console.log("Yes, this is a palindrome");
else
console.log("Nope! It isnt a palindrome");
Here is a solution that works even if the string contains non-alphanumeric characters.
function isPalindrome(str) {
str = str.toLowerCase().replace(/\W+|_/g, '');
return str == str.split('').reverse().join('');
}

How to check if a string contains at least 2 letters

I need to check if test contains at least 2 letters, like SC.
var test='SC129h';
if (test.containsalphabets atleast 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
Create a regular expression to match all characters in the string that are in the alphabet, and count them.
var test = "SC129h";
if((test.match(/[A-Za-z]/g).length || 0) >= 2) {
alert("success");
}
Alternatively, to be more efficient, do a linear search and check the ASCII code. This can avoid scanning the whole string.
var test = "SC129h";
var matches = 0;
for(var i = 0; i < test.length; i++) {
if((test[i] >= 'a' && test[i] <= 'z') || (test[i] >= 'A' && test[i] <= 'Z')) {
matches++;
if(matches > 2) break;
}
}
if(matches >= 2) {
// Do something here
}
You should be using the RegEx pattern:
/([A-Za-z])/g
And check for the length of the test to be more than 2.
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match.length >= 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
Better Version
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match[1]) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
You can also remove all non alphabetic characters then checking for the length of the result.
'SC129h'.replace(/[^a-z]/gi,'').length > 1
you could do var match = /[a-z]{2,}/gi.test(test) with would return a Boolean

Failed test for JavaScript palindrome

I noticed when I literally type the word test or dabd, it fails by saying "test is a palindrome"; obviously these should fail. I test other words like racecar, madam, cat, they all pass. I check from the left most character and right most character and go down until we reach the middle. What could be the issue?
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome(str);
}
function palindrome(str) {
var j = str.length;
if (/\s/.test(str)) {
alert("No spaces allowed.")
return false;
}
for (i = 0; i < j / 2; i++) {
if (str[i] == str[j - 1 - i]) {
isPalindrome('', str);
return true;
} else {
notPalindrome(str);
return false;
}
}
}
function isPalindrome(e, str) {
alert(str + " is a Palindrome.");
}
function notPalindrome(str) {
alert(str + " isn't a Palindrome");
}
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", lengthChecker);
});
In palindrome() you always only check the first character and immediately return. Fix the loop like this:
for (var i = 0; i < j / 2; i++) {
if (str[i] != str[j - 1 - i]) {
notPalindrome(str);
return false;
}
}
isPalindrome('', str);
return true;
For reference, you don't need to loop. You can simplify the palindrome test to just this:
str === str.split('').reverse().join('')
This splits the string into an array, which can then be reversed. It then joins it back into a string so you can compare it.
I'd then put this in a ternary statement for modifying the message:
var notp = (str === '' || str !== str.split('').reverse().join('').replace(" ", "")) ? 'is NOT':'IS';
I added "str === ''" to test for non-entries, and I added a remove spaces test as well. Now you've got a variable that you can push into a generic alert or whatever. You can change that to read "true:false;" instead is you want to control more than just the text of the message.
The following gets rid of the leading and trailing spaces:
str = str.trim();
There are more edits you can make, but this should help you along. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/fudLdx0r/

Palindrome check in Javascript

I have the following:
function checkPalindrom(palindrom)
{
for( var i = palindrom.length; i > 0; i-- )
{
if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
{
document.write('the word is palindrome.');
}else{
document.write('the word is not palindrome!');
}
}
}
checkPalindrom('wordthatwillbechecked');
What is wrong with my code? I want to check if the word is a palindrome.
Maybe I will suggest alternative solution:
function checkPalindrom (str) {
return str == str.split('').reverse().join('');
}
UPD. Keep in mind however that this is pretty much "cheating" approach, a demonstration of smart usage of language features, but not the most practical algorithm (time O(n), space O(n)). For real life application or coding interview you should definitely use loop solution. The one posted by Jason Sebring in this thread is both simple and efficient (time O(n), space O(1)).
25x faster than the standard answer
function isPalindrome(s,i) {
return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}
use like:
isPalindrome('racecar');
as it defines "i" itself
Fiddle: http://jsfiddle.net/namcx0yf/9/
This is ~25 times faster than the standard answer below.
function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
Fiddle: http://jsfiddle.net/t0zfjfab/2/
View console for performance results.
Although the solution is difficult to read and maintain, I would recommend understanding it to demonstrate non-branching with recursion and bit shifting to impress your next interviewer.
explained
The || and && are used for control flow like "if" "else". If something left of || is true, it just exits with true. If something is false left of || it must continue. If something left of && is false, it exits as false, if something left of a && is true, it must continue. This is considered "non-branching" as it does not need if-else interupts, rather its just evaluated.
1. Used an initializer not requiring "i" to be defined as an argument. Assigns "i" to itself if defined, otherwise initialize to 0. Always is false so next OR condition is always evaluated.
(i = i || 0) < 0
2. Checks if "i" went half way but skips checking middle odd char. Bit shifted here is like division by 2 but to lowest even neighbor division by 2 result. If true then assumes palindrome since its already done. If false evaluates next OR condition.
i >= s.length >> 1
3. Compares from beginning char and end char according to "i" eventually to meet as neighbors or neighbor to middle char. If false exits and assumes NOT palindrome. If true continues on to next AND condition.
s[i] == s[s.length-1-i]
4. Calls itself again for recursion passing the original string as "s". Since "i" is defined for sure at this point, it is pre-incremented to continue checking the string's position. Returns boolean value indicating if palindrome.
isPalindrome(s,++i)
BUT...
A simple for loop is still about twice as fast as my fancy answer (aka KISS principle)
function fastestIsPalindrome(str) {
var len = Math.floor(str.length / 2);
for (var i = 0; i < len; i++)
if (str[i] !== str[str.length - i - 1])
return false;
return true;
}
http://jsfiddle.net/6L953awz/1/
The logic here is not quite correct, you need to check every letter to determine if the word is a palindrome. Currently, you print multiple times. What about doing something like:
function checkPalindrome(word) {
var l = word.length;
for (var i = 0; i < l / 2; i++) {
if (word.charAt(i) !== word.charAt(l - 1 - i)) {
return false;
}
}
return true;
}
if (checkPalindrome("1122332211")) {
document.write("The word is a palindrome");
} else {
document.write("The word is NOT a palindrome");
}
Which should print that it IS indeed a palindrome.
First problem
= is assign
== is compare
Second problem, Your logic here is wrong
palindrom.charAt(palindrom.length)-1
You are subtracting one from the charAt and not the length.
Third problem, it still will be wrong since you are not reducing the length by i.
It works to me
function palindrome(str) {
/* remove special characters, spaces and make lowercase*/
var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if str is a Palindrome*/
return (removeChar === checkPalindrome);
}
As a much clearer recursive function: http://jsfiddle.net/dmz2x117/
function isPalindrome(letters) {
var characters = letters.split(''),
firstLetter = characters.shift(),
lastLetter = characters.pop();
if (firstLetter !== lastLetter) {
return false;
}
if (characters.length < 2) {
return true;
}
return isPalindrome(characters.join(''));
}
SHORTEST CODE (31 chars)(ES6):
p=s=>s==[...s].reverse().join``
p('racecar'); //true
Keep in mind short code isn't necessarily the best. Readability and efficiency can matter more.
At least three things:
You are trying to test for equality with =, which is used for setting. You need to test with == or ===. (Probably the latter, if you don't have a reason for the former.)
You are reporting results after checking each character. But you don't know the results until you've checked enough characters.
You double-check each character-pair, as you really only need to check if, say first === last and not also if last === first.
function checkPalindrom(palindrom)
{
var flag = true;
var j = 0;
for( var i = palindrom.length-1; i > palindrom.length / 2; i-- )
{
if( palindrom[i] != palindrom[j] )
{
flag = false;
break; // why this? It'll exit the loop at once when there is a mismatch.
}
j++;
}
if( flag ) {
document.write('the word is palindrome.');
}
else {
document.write('the word is not palindrome.');
}
}
checkPalindrom('wordthatwillbechecked');
Why am I printing the result outside the loop? Otherwise, for each match in the word, it'll print "is or is not pallindrome" rather than checking the whole word.
EDIT: Updated with changes and a fix suggested by Basemm.
I've added some more to the above functions, to check strings like, "Go hang a salami, I'm a lasagna hog".
function checkPalindrom(str) {
var str = str.replace(/[^a-zA-Z0-9]+/gi, '').toLowerCase();
return str == str.split('').reverse().join('');
}
Thanks
The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.
Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.
isPalindrome():
Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.
for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.
Here's the code:
/**
* TODO: If func counts out, let it return 0
* * Assume !isPalindrome (invert logic)
*/
function isPalindrome(S){
var s = S
, len = s.length
, mid = len/2;
, i = 0, j = len-1;
while(i<mid){
var l = s.charAt(i);
while(j>=mid){
var r = s.charAt(j);
if(l === r){
console.log('#while *', i, l, '...', j, r);
--j;
break;
}
console.log('#while !', i, l, '...', j, r);
return 0;
}
++i;
}
return 1;
}
var nooe = solution('neveroddoreven'); // even char length
var kayak = solution('kayak'); // odd char length
var kayaks = solution('kayaks');
console.log('#isPalindrome', nooe, kayak, kayaks);
Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.
function palindromCheck(str) {
var palinArr, i,
palindrom = [],
palinArr = str.split(/[\s!.?,;:'"-()]/ig);
for (i = 0; i < palinArr.length; i++) {
if (palinArr[i].toLowerCase() === palinArr[i].split('').reverse().join('').toLowerCase() &&
palinArr[i] !== '') {
palindrom.push(palinArr[i]);
}
}
return palindrom.join(', ');
}
console.log(palindromCheck('There is a man, his name! was Bob.')); //a, Bob
Finds and upper to lower case. Split string into array, I don't know why a few white spaces remain, but I wanted to catch and single letters.
= in palindrom[i] = palindrom.charAt(palindrom.length)-1 should be == or ===
palindrom.charAt(palindrom.length)-1 should be palindrom.charAt(palindrom.length - i)
Sharing my fast variant which also support spaces
function isPalindrom(str) {
var ia = 0;
var ib = str.length - 1;
do {
if (str[ia] === str[ib]) continue;
// if spaces skip & retry
if (str[ia] === ' ' && ib++) continue;
if (str[ib] === ' ' && ia--) continue;
return false;
} while (++ia < --ib);
return true;
}
var palindrom="never odd or even";
var res = isPalindrom(palindrom);
document.getElementById('check').innerHTML ='"'+ palindrom + '"'+" checked to be :" +res;
<span id="check" />
Some above short anwsers is good, but it's not easy for understand, I suggest one more way:
function checkPalindrome(inputString) {
if(inputString.length == 1){
return true;
}else{
var i = 0;
var j = inputString.length -1;
while(i < j){
if(inputString[i] != inputString[j]){
return false;
}
i++;
j--;
}
}
return true;
}
I compare each character, i start form left, j start from right, until their index is not valid (i<j).
It's also working in any languages
One more solution with ES6
isPalin = str => [...str].every((c, i) => c === str[str.length-1-i]);
You can try the following
function checkPalindrom (str) {
str = str.toLowerCase();
return str == str.split('').reverse().join('');
}
if(checkPalindrom('Racecar')) {
console.log('Palindrome');
} else {
console.log('Not Palindrome');
}
function checkPalindrom(palindrom)
{
palindrom= palindrom.toLowerCase();
var flag = true;
var j;
j = (palindrom.length) -1 ;
//console.log(j);
var cnt = j / 2;
//console.log(cnt);
for( i = 0; i < cnt+1 ; i++,j-- )
{
console.log("J is => "+j);
console.log(palindrom[i] + "<==>" + palindrom[j]);
if( palindrom[i] != palindrom[j] )
{
flag = false;
break;
}
}
if( flag ) {
console.log('the word is palindrome.');
}
else {
console.log('the word is not palindrome.');
}
}
checkPalindrom('Avid diva');
I'm wondering why nobody suggested this:
ES6:
// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
isPalindrom = (str = "") => {
if (str[0] === str[str.length - 1]) {
return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
}
return false;
}
alert(["aba", "acb", "aa", "abba", "s"].map((e, i) => isPalindrom(e)).join())
ES5:
// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
function isPalindrom(str) => {
var str = typeof str !== "string" ? "" : str;
if (str[0] === str[str.length - 1]) {
return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
}
return false;
}
alert(["aba", "acb", "aa", "abba", "s"].map(function (e, i) {
return isPalindrom(e);
}).join());
Recursive Method:
var low;
var high;
var A = "abcdcba";
function palindrome(A , low, high){
A = A.split('');
if((low > high) || (low == high)){
return true;
}
if(A[low] === A[high]){
A = A.join('');
low = low + 1;
high = high - 1;
return palindrome(A , low, high);
}
else{
return "not a palindrome";
}
}
palindrome(A, 0, A.length-1);
I thought I'd share my own solution:
function palindrome(string){
var reverseString = '';
for(var k in string){
reverseString += string[(string.length - k) - 1];
}
if(string === reverseString){
console.log('Hey there palindrome');
}else{
console.log('You are not a palindrome');
}
}
palindrome('ana');
Hope will help someone.
I found this on an interview site:
Write an efficient function that checks whether any permutation of an
input string is a palindrome. You can ignore punctuation, we only care
about the characters.
Playing around with it I came up with this ugly piece of code :)
function checkIfPalindrome(text) {
var found = {};
var foundOne = 0;
text = text.replace(/[^a-z0-9]/gi, '').toLowerCase();
for (var i = 0; i < text.length; i++) {
if (found[text[i]]) {
found[text[i]]++;
} else {
found[text[i]] = 1;
}
}
for (var x in found) {
if (found[x] === 1) {
foundOne++;
if (foundOne > 1) {
return false;
}
}
}
for (var x in found) {
if (found[x] > 2 && found[x] % 2 && foundOne) {
return false;
}
}
return true;
}
Just leaving it here for posterity.
How about this, using a simple flag
function checkPalindrom(str){
var flag = true;
for( var i = 0; i <= str.length-1; i++){
if( str[i] !== str[str.length - i-1]){
flag = false;
}
}
if(flag == false){
console.log('the word is not a palindrome!');
}
else{
console.log('the word is a palindrome!');
}
}
checkPalindrom('abcdcba');
(JavaScript) Using regexp, this checks for alphanumeric palindrome and disregards space and punctuation.
function palindrome(str) {
str = str.match(/[A-Za-z0-9]/gi).join("").toLowerCase();
// (/[A-Za-z0-9]/gi) above makes str alphanumeric
for(var i = 0; i < Math.floor(str.length/2); i++) { //only need to run for half the string length
if(str.charAt(i) !== str.charAt(str.length-i-1)) { // uses !== to compare characters one-by-one from the beginning and end
return "Try again.";
}
}
return "Palindrome!";
}
palindrome("A man, a plan, a canal. Panama.");
//palindrome("4_2 (: /-\ :) 2-4"); // This solution would also work on something like this.
`
function checkPalindrome (str) {
var str = str.toLowerCase();
var original = str.split(' ').join('');
var reversed = original.split(' ').reverse().join('');
return (original === reversed);
}
`
This avoids regex while also dealing with strings that have spaces and uppercase...
function isPalindrome(str) {
str = str.split("");
var str2 = str.filter(function(x){
if(x !== ' ' && x !== ',') {
return x;
}
});
return console.log(str2.join('').toLowerCase()) == console.log(str2.reverse().join('').toLowerCase());
};
isPalindrome("A car, a man, a maraca"); //true
function myPolidrome(polidrome){
var string=polidrome.split('').join(',');
for(var i=0;i<string.length;i++){
if(string.length==1){
console.log("is polidrome");
}else if(string[i]!=string.charAt(string.length-1)){
console.log("is not polidrome");
break;
}else{
return myPolidrome(polidrome.substring(1,polidrome.length-1));
}
}
}
myPolidrome("asasdsdsa");
Thought I will share my solution using Array.prototype.filter(). filter()
filters the array based on boolean values the function returns.
var inputArray=["","a","ab","aba","abab","ababa"]
var outputArray=inputArray.filter(function isPalindrome(x){
if (x.length<2) return true;
var y=x.split("").reverse().join("");
return x==y;
})
console.log(outputArray);
This worked for me.
var number = 8008
number = number + "";
numberreverse = number.split("").reverse().join('');
console.log ("The number if reversed is: " +numberreverse);
if (number == numberreverse)
console.log("Yes, this is a palindrome");
else
console.log("Nope! It isnt a palindrome");
Here is a solution that works even if the string contains non-alphanumeric characters.
function isPalindrome(str) {
str = str.toLowerCase().replace(/\W+|_/g, '');
return str == str.split('').reverse().join('');
}

How to do case insensitive string comparison?

How do I perform case insensitive string comparison in JavaScript?
The simplest way to do it (if you're not worried about special Unicode characters) is to call toUpperCase:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
EDIT: This answer was originally added 9 years ago. Today you should use localeCompare with the sensitivity: 'accent' option:
function ciEquals(a, b) {
return typeof a === 'string' && typeof b === 'string'
? a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0
: a === b;
}
console.log("'a' = 'a'?", ciEquals('a', 'a'));
console.log("'AaA' = 'aAa'?", ciEquals('AaA', 'aAa'));
console.log("'a' = 'á'?", ciEquals('a', 'á'));
console.log("'a' = 'b'?", ciEquals('a', 'b'));
The { sensitivity: 'accent' } tells localeCompare() to treat two variants of the same base letter as the same unless they have different accents (as in the third example) above.
Alternatively, you can use { sensitivity: 'base' }, which treats two characters as equivalent as long as their base character is the same (so A would be treated as equivalent to á).
Note that the third parameter of localeCompare is not supported in IE10 or lower or certain mobile browsers (see the compatibility chart on the page linked above), so if you need to support those browsers, you'll need some kind of fallback:
function ciEqualsInner(a, b) {
return a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0;
}
function ciEquals(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') {
return a === b;
}
// v--- feature detection
return ciEqualsInner('A', 'a')
? ciEqualsInner(a, b)
: /* fallback approach here */;
}
Original answer
The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.
Case-insensitive search
When both strings being compared are variables (not constants), then it's a little more complicated 'cause you need to generate a RegExp from the string but passing the string to RegExp constructor can result in incorrect matches or failed matches if the string has special regex characters in it.
If you care about internationalization don't use toLowerCase() or toUpperCase() as it doesn't provide accurate case-insensitive comparisons in all languages.
http://www.i18nguy.com/unicode/turkish-i18n.html
As said in recent comments, string::localeCompare supports case insensitive comparisons (among other powerful things).
Here's a simple example
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
And a generic function you could use
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
Note that instead of undefined you should probably enter the specific locale you are working with. This is important as denoted in the MDN docs
in Swedish, ä and a are separate base letters
Sensitivity options
Browser support
As of time of posting, UC Browser for Android and Opera Mini do not support locale and options parameters. Please check https://caniuse.com/#search=localeCompare for up to date info.
Update:
As per the comments, previous answer checks for source contains keyword, to make it equality check added ^ and $.
(/^keyword$/i).test(source)
With the help of regular expression also we can achieve.
(/keyword/i).test(source)
/i is for ignoring case. If not necessary we can ignore and test for NOT case sensitive matches like
(/keyword/).test(source)
Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).
function compareStrings (string1, string2, ignoreCase, useLocale) {
if (ignoreCase) {
if (useLocale) {
string1 = string1.toLocaleLowerCase();
string2 = string2.toLocaleLowerCase();
}
else {
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
}
}
return string1 === string2;
}
if you are concerned about the direction of the inequality (perhaps you want to sort a list)
you pretty-much have to do case-conversion, and as there are more lowercase characters in unicode than uppercase toLowerCase is probably the best conversion to use.
function my_strcasecmp( a, b )
{
if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1
if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
return 0
}
Javascript seems to use locale "C" for string comparisons so the resulting ordering will
be ugly if the strings contain other than ASCII letters. there's not much that can be done about that without doing much more detailed inspection of the strings.
I have recently created a micro library that provides case-insensitive string helpers: https://github.com/nickuraltsev/ignore-case. (It uses toUpperCase internally.)
var ignoreCase = require('ignore-case');
ignoreCase.equals('FOO', 'Foo'); // => true
ignoreCase.startsWith('foobar', 'FOO'); // => true
ignoreCase.endsWith('foobar', 'BaR'); // => true
ignoreCase.includes('AbCd', 'c'); // => true
ignoreCase.indexOf('AbCd', 'c'); // => 2
Use RegEx for string match or comparison.
In JavaScript, you can use match() for string comparison,
don't forget to put i in the regular expression. This flag will force case insensitive testing.
Example:
To confirm the string test of any case is included anywhere inside the matchString variable
var matchString = "Test";
if (matchString.match(/test/i)) {
alert('matchString contains the substring "test" case insensitive');
}
else {
alert('matchString does not contain the substring "test" case insensitive');
}
To confirm matchString variable only contains test of any case, and no additional characters, then use zero-width assertions ^ and $ in the regular expression. These will require test to appear directly after the start of the string and directly before the end of the string respecitivly.
var matchString = "Test";
if (matchString.match(/^test$/i)) {
alert('matchString equals "test" case insensitive');
}
else {
alert('matchString does not equal "test" case insensitive');
}
Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:
Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.
Taking points (1) and (2) into consideration, an example would be:
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
}
Lots of answers here, but I like to add a sollution based on extending the String lib:
String.prototype.equalIgnoreCase = function(str)
{
return (str != null
&& typeof str === 'string'
&& this.toUpperCase() === str.toUpperCase());
}
This way you can just use it like you do in Java!
Example:
var a = "hello";
var b = "HeLLo";
var c = "world";
if (a.equalIgnoreCase(b)) {
document.write("a == b");
}
if (a.equalIgnoreCase(c)) {
document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
document.write("b != c");
}
Output will be:
"a == b"
"b != c"
String.prototype.equalIgnoreCase = function(str) {
return (str != null &&
typeof str === 'string' &&
this.toUpperCase() === str.toUpperCase());
}
var a = "hello";
var b = "HeLLo";
var c = "world";
if (a.equalIgnoreCase(b)) {
document.write("a == b");
document.write("<br>");
}
if (a.equalIgnoreCase(c)) {
document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
document.write("b != c");
}
There are two ways for case insensitive comparison:
Convert strings to upper case and then compare them using the strict operator (===).
Pattern matching using string methods:
Use the "search" string method for case insensitive search.
<!doctype html>
<html>
<head>
<script>
// 1st way
var a = "apple";
var b = "APPLE";
if (a.toUpperCase() === b.toUpperCase()) {
alert("equal");
}
//2nd way
var a = " Null and void";
document.write(a.search(/null/i));
</script>
</head>
</html>
If both strings are of the same known locale, you may want to use Intl.Collator object like this:
function equalIgnoreCase(s1: string, s2: string) {
return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}
Obviously, you may want to cache the Collator for better efficiency.
The advantages of this approach is that it should be much faster than using RegExps and is based on an extremely customizable (see description of locales and options constructor parameters in the article above) set of ready-to-use collators.
I like this quick shorthand variation -
export const equalsIgnoreCase = (str1, str2) => {
return (!str1 && !str2) || (str1 && str2 && str1.toUpperCase() == str2.toUpperCase())
}
Quick in processing, and does what it is intended to.
I wrote a extension. very trivial
if (typeof String.prototype.isEqual!= 'function') {
String.prototype.isEqual = function (str){
return this.toUpperCase()==str.toUpperCase();
};
}
str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
console.log("true");
}
Even this question has already been answered. I have a different approach to using RegExp and match to ignore case sensitivity. Please see my link
https://jsfiddle.net/marchdave/7v8bd7dq/27/
$("#btnGuess").click(guessWord);
function guessWord() {
var letter = $("#guessLetter").val();
var word = 'ABC';
var pattern = RegExp(letter, 'gi'); // pattern: /a/gi
var result = word.match(pattern);
alert('Ignore case sensitive:' + result);
}
Convert both to lower string (only once for performance reasons) and compare them with inline ternary operator:
function strcasecmp(s1,s2){
s1=(s1+'').toLowerCase();
s2=(s2+'').toLowerCase();
return s1>s2?1:(s1<s2?-1:0);
}
How about NOT throwing exceptions and NOT using slow regex?
return str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase();
The above snippet assumes you don't want to match if either string is null or undefined.
If you want to match null/undefined, then:
return (str1 == null && str2 == null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
If for some reason you care about undefined vs null:
return (str1 === undefined && str2 === undefined)
|| (str1 === null && str2 === null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
Since no answer clearly provided a simple code snippet for using RegExp, here's my attempt:
function compareInsensitive(str1, str2){
return typeof str1 === 'string' &&
typeof str2 === 'string' &&
new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}
It has several advantages:
Verifies parameter type (any non-string parameter, like undefined for example, would crash an expression like str1.toUpperCase()).
Does not suffer from possible internationalization issues.
Escapes the RegExp string.
If you know you're dealing with ascii text then you can just use a uppercase/lowercase character offset comparison.
Just make sure the string your "perfect" string (the one you want to match against) is lowercase:
const CHARS_IN_BETWEEN = 32;
const LAST_UPPERCASE_CHAR = 90; // Z
function strMatchesIgnoreCase(lowercaseMatch, value) {
let i = 0, matches = lowercaseMatch.length === value.length;
while (matches && i < lowercaseMatch.length) {
const a = lowercaseMatch.charCodeAt(i);
const A = a - CHARS_IN_BETWEEN;
const b = value.charCodeAt(i);
const B = b + ((b > LAST_UPPERCASE_CHAR) ? -CHARS_IN_BETWEEN : CHARS_IN_BETWEEN);
matches = a === b // lowerA === b
|| A === b // upperA == b
|| a === B // lowerA == ~b
|| A === B; // upperA == ~b
i++;
}
return matches;
}
For better browser compatibility you can rely on a regular expression. This will work in all web browsers released in the last 20 years:
String.prototype.equalsci = function(s) {
var regexp = RegExp("^"+this.replace(/[.\\+*?\[\^\]$(){}=!<>|:-]/g, "\\$&")+"$", "i");
return regexp.test(s);
}
"PERSON#Ü.EXAMPLE.COM".equalsci("person#ü.example.com")// returns true
This is different from the other answers found here because it takes into account that not all users are using modern web browsers.
Note: If you need to support unusual cases like the Turkish language you will need to use localeCompare because i and I are not the same letter in Turkish.
"I".localeCompare("i", undefined, { sensitivity:"accent"})===0// returns true
"I".localeCompare("i", "tr", { sensitivity:"accent"})===0// returns false
This is an improved version of this answer.
String.equal = function (s1, s2, ignoreCase, useLocale) {
if (s1 == null || s2 == null)
return false;
if (!ignoreCase) {
if (s1.length !== s2.length)
return false;
return s1 === s2;
}
if (useLocale) {
if (useLocale.length)
return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)
else
return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()
}
else {
if (s1.length !== s2.length)
return false;
return s1.toLowerCase() === s2.toLowerCase();
}
}
Usages & tests:
String.equal = function (s1, s2, ignoreCase, useLocale) {
if (s1 == null || s2 == null)
return false;
if (!ignoreCase) {
if (s1.length !== s2.length)
return false;
return s1 === s2;
}
if (useLocale) {
if (useLocale.length)
return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)
else
return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()
}
else {
if (s1.length !== s2.length)
return false;
return s1.toLowerCase() === s2.toLowerCase();
}
}
// If you don't mind extending the prototype.
String.prototype.equal = function(string2, ignoreCase, useLocale) {
return String.equal(this.valueOf(), string2, ignoreCase, useLocale);
}
// ------------------ TESTS ----------------------
console.log("Tests...");
console.log('Case sensitive 1');
var result = "Abc123".equal("Abc123");
console.assert(result === true);
console.log('Case sensitive 2');
result = "aBC123".equal("Abc123");
console.assert(result === false);
console.log('Ignore case');
result = "AbC123".equal("aBc123", true);
console.assert(result === true);
console.log('Ignore case + Current locale');
result = "AbC123".equal("aBc123", true);
console.assert(result === true);
console.log('Turkish test 1 (ignore case, en-US)');
result = "IiiI".equal("ıiİI", true, "en-US");
console.assert(result === false);
console.log('Turkish test 2 (ignore case, tr-TR)');
result = "IiiI".equal("ıiİI", true, "tr-TR");
console.assert(result === true);
console.log('Turkish test 3 (case sensitive, tr-TR)');
result = "IiiI".equal("ıiİI", false, "tr-TR");
console.assert(result === false);
console.log('null-test-1');
result = "AAA".equal(null);
console.assert(result === false);
console.log('null-test-2');
result = String.equal(null, "BBB");
console.assert(result === false);
console.log('null-test-3');
result = String.equal(null, null);
console.assert(result === false);
We could also do this using ASCII:
function toLower(a){
let c = "";
for(let i = 0;i<a.length;i++){
let f = a.charCodeAt(i);
if(f < 95){
c += String.fromCharCode(f+32);
}
else{
c += a[i];
}
}
return c;
}
function compareIt(a,b){
return toLower(a)==toLower(b);
}
console.log(compareIt("An ExamPlE" , "an example"));

Categories