[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 850
  • Last Modified:

JavaScript: Case insensitive test against each item in array

I use the code below to test a string against each item in array.  (Thanks, sjklein42)

Now I want it to be case insensitive.  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>

<script type="text/javascript">
/*<![CDATA[*/

Array.prototype.contains = function(obj) {
  // Thanks, sjklein42
  var i = this.length;
  while (i--) {
    if (obj.indexOf(this[i].toLowerCase()) != (-1))
    {
      return true;
    }
  }
  return false;
}

var badStuff = new Array("aaa","bbb","ccc","ddd","EEE");

var v = 'AAA hello world';
alert(badStuff.contains(v)); // should alert true because v contains aaa and aaa is in the baddStuff array

var v = 'This is a bbbbbbbb test';
alert(badStuff.contains(v)); // should alert true because v contains bbb and bbb is in the baddStuff array

var v = 'Hello World';
alert(badStuff.contains(v)); // should alert false

var v = 'CCC';
alert(badStuff.contains(v)); // should alert true

/*]]>*/
</script>

</head>
<body>

<h1>Hello World</h1>

</body>
</html>

Open in new window

0
hankknight
Asked:
hankknight
  • 2
3 Solutions
 
David S.Commented:
You're close. You just need to make sure that they're both lowercase.
Array.prototype.contains = function(obj) {
  // Thanks, sjklein42
  var i = this.length;
  obj = obj.toLowerCase();
  while (i--) {
    if (obj.indexOf(this[i].toLowerCase()) != -1)
    {
      return true;
    }
  }
  return false;
}

Open in new window

0
 
leakim971PluritechnicianCommented:
replace line 13 by :
 if (obj.toLowerCase().indexOf(this[i].toLowerCase()) != (-1))

Open in new window

0
 
sjklein42Commented:
Fixed your parens

    if ((obj.toLowerCase()).indexOf(this[i]) != (-1))

Open in new window

0
 
sjklein42Commented:
For my solution, you should also change the badStuff line to be all lower case.  Then you don't need to lower-case it every time it is used.

var badStuff = new Array("aaa","bbb","ccc","ddd","eee");

Open in new window

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now