Javascript 正则表达式检查字符串是否以 开头,忽略大小写差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14978625/
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
Regex to check whether string starts with, ignoring case differences
提问by Rajat Gupta
I need to check whether a word starts with a particular substring ignoring the case differences. I have been doing this check using the following regex search pattern but that does not help when there is difference in case across the strings.
我需要检查一个单词是否以特定的子字符串开头而忽略大小写差异。我一直在使用以下正则表达式搜索模式进行此检查,但是当字符串之间的大小写不同时,这无济于事。
my case sensitive way:
我区分大小写的方式:
var searchPattern = new RegExp('^' + query);
if (searchPattern.test(stringToCheck)) {}
回答by Felix Kling
Pass the imodifier as second argument:
将i修饰符作为第二个参数传递:
new RegExp('^' + query, 'i');
Have a look at the documentationfor more information.
查看文档以获取更多信息。
回答by Guffa
You don't need a regular expression at all, just compare the strings:
您根本不需要正则表达式,只需比较字符串:
if (stringToCheck.substr(0, query.length).toUpperCase() == query.toUpperCase())
Demo: http://jsfiddle.net/Guffa/AMD7V/
演示:http: //jsfiddle.net/Guffa/AMD7V/
This also handles cases where you would need to escape characters to make the RegExp solution work, for example if query="4*5?"which would always match everything otherwise.
这也处理您需要转义字符以使 RegExp 解决方案工作的情况,例如,如果query="4*5?"它总是匹配其他所有内容。
回答by grepit
I think all the previous answers are correct. Here is another example similar to SERPRO's, but the difference is that there is no new constructor:
我认为以前的所有答案都是正确的。这是另一个类似于 SERPRO 的示例,但不同之处在于没有新的构造函数:
Notice:iignores the case and ^means "starts with".
注意:i忽略大小写并^表示“开始于”。
var whateverString = "My test String";
var pattern = /^my/i;
var result = pattern.test(whateverString);
if (result === true) {
console.log(pattern, "pattern matched!");
} else {
console.log(pattern, "pattern did NOT match!");
}
Here is the jsfiddle(old version) if you would like to give it a try.
如果您想尝试一下,这里是jsfiddle(旧版本)。


