12

In JavaScript, I'm trying using the user's input to search my database. For example, user input is "monster", and my database's data is "Monster". How can I have it match regardless of it's casing?

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
Strawberry
  • 66,024
  • 56
  • 149
  • 197
  • Are you looking for something like this: http://stackoverflow.com/questions/177719/javascript-case-insensitive-search – zengr Apr 12 '10 at 00:20
  • @zengr I don't think that's what they're looking for. This regards searching a database as opposed to searching the string :D – Gordon Gustafson Apr 12 '10 at 00:22

4 Answers4

23

Javascript string case-insensitive comparisons can be performed with string.toUpperCase.

if (input.toUpperCase() === "OTHER STRING")
    ....

(I'm assuming your database example is just an example as databases usually ignore the case of strings :)

Community
  • 1
  • 1
Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
1

Use match() instead of search().

Gugan
  • 1,625
  • 2
  • 27
  • 65
0

You should convert both javascript string and database where clause to use lower case string.

But I guess database like sql server and mysql are all case insensitive in terms of string.

zs2020
  • 53,766
  • 29
  • 154
  • 219
-1

If you're using AJAX then you're using a server side language. Why don't you let the server side script normalize the data?. You could even delegate this task to the database, using the proper UPPER and LOWER functions, but for security reasons data normalization should be a task for the server side script.

You can use JS to pre-check the data in terms of length and syntaxes, mostly for helping and preventing the user from making mistakes, but one thing you should never do is query untreated JS data. Anyone could manipulate the JS and query a' OR 1=1; DROP TABLE users;--, even if you validate the data.

Ben
  • 16,275
  • 9
  • 45
  • 63