Reputation: 357
I am trying to convert two strings to same format like toUpperCase/toLowerCase to compare two strings regardless of case sensitive in javaScript. Below is my function.
function submitForm() {
var usernames=['one','two','Test'];
var cpusername = "test";
var flag = 0;
if (cpusername !== "")
{
for (var k = 0; k < usernames.length; k++)
{
var upperCasecpusername=cpusername.toUpperCase();
var getusername= usernames[k];
var upperCaseusername=getusername.toUpperCase();
if (upperCasecpusername === upperCaseusername)
{
flag=1;
console.log(flag);
//document.getElementById('cpusername').value = '';
$.messager.alert("Message", "Someone already has username"+cpusername+". Try another!!", '');
}
}
}
am getting this error Uncaught TypeError: Cannot read property 'toUpperCase' of undefined .I have also tried to convert toString() first and then to toLowercase() .It was also erred (toString() undefined). Also suggest me if any other ways to compare two string regardless of case sensitive. Thanks!
Upvotes: 2
Views: 43180
Reputation: 34
Using functions .toLowerCase()
& .toUpperCase()
are fine, but as requested to other way to string case insensitive comparison, I would recommend to use regex
.
Try something like this for case insensitive string comparison
var str= "TEST";
var result = str.match(/test/i);
if(result){
// Write logic once the match found
}
Upvotes: 1
Reputation: 11808
Try This
js code
jQuery( document ).ready(function() {
var usernames=['one','two','Test'];
var cpusername = "test";
var flag = 0;
if (cpusername !== "")
{
for (var k = 0; k < usernames.length; k++)
{
var upperCasecpusername=cpusername.toLowerCase();
var getusername= usernames[k];
console.log(getusername);
var upperCaseusername=getusername.toLowerCase();
if (upperCasecpusername === upperCaseusername)
{
console.log(upperCasecpusername);
console.log(upperCaseusername);
flag=1;
console.log(flag);
//document.getElementById('cpusername').value = '';
alert( "Someone already has username"+cpusername+". Try another!!", '');
}
}
}
});
You can view demo here
Upvotes: 1
Reputation: 194
Try this:
var getusername= ""+usernames[k];
If that doesn't work, then this could be the problem:
Switch
for (var k = 0; k <= usernames.length; k++)
for
for (var k = 0; k <= usernames.length-1; k++)
Upvotes: 4