javascript:忽略字符串的区分大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2619260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: ignoring case sensitivity of strings
提问by Strawberry
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?
在 JavaScript 中,我尝试使用用户的输入来搜索我的数据库。例如,用户输入是“monster”,而我的数据库的数据是“Monster”。不管它的外壳如何,我怎样才能让它匹配?
回答by Gordon Gustafson
Javascript string case-insensitive comparisons can be performed with string.toUpperCase.
可以使用string.toUpperCase执行 Javascript 字符串不区分大小写的比较。
if (input.toUpperCase() === "OTHER STRING")
....
(I'm assuming your database example is just an example as databases usually ignore the case of strings :)
(我假设您的数据库示例只是一个示例,因为数据库通常会忽略字符串的大小写:)
回答by Gugan
Use match() instead of search().
使用 match() 而不是 search()。
回答by zs2020
You should convert both javascript string and database where clause to use lower case string.
您应该将 javascript 字符串和数据库 where 子句转换为使用小写字符串。
But I guess database like sql server and mysql are all case insensitive in terms of string.
但我想像 sql server 和 mysql 这样的数据库在字符串方面都是不区分大小写的。
回答by Ben
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.
如果您使用 AJAX,那么您使用的是服务器端语言。为什么不让服务器端脚本规范化数据?您甚至可以使用适当的 UPPER 和 LOWER 函数将此任务委托给数据库,但出于安全原因,数据规范化应该是服务器端脚本的任务。
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.
您可以使用 JS 在长度和语法方面对数据进行预检查,主要是为了帮助和防止用户出错,但您永远不应该做的一件事是查询未经处理的 JS 数据。任何人都可以操作 JS 和 query a' OR 1=1; DROP TABLE users;--,即使您验证了数据。

