简体   繁体   English

JavaScript 中不区分大小写的正则表达式

[英]Case insensitive regex in JavaScript

I want to extract a query string from my URL using JavaScript, and I want to do a case insensitive comparison for the query string name.我想使用 JavaScript 从我的 URL 中提取查询字符串,并且我想对查询字符串名称进行不区分大小写的比较。 Here is what I am doing:这是我在做什么:

var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;

But the above code does a case sensitive search.但是上面的代码做了区分大小写的搜索。 I tried /<regex>/i but it did not help.我试过/<regex>/i但它没有帮助。 Any idea how can that be achieved?知道如何实现吗?

您可以添加“i”修饰符,表示“忽略大小写”

var results = new RegExp('[\\?&]' + name + '=([^&#]*)', 'i').exec(window.location.href);

修饰符作为第二个参数给出:

new RegExp('[\\?&]' + name + '=([^&#]*)', "i")

Simple one liner.简单的一个班轮。 In the example below it replaces every vowel with an X.在下面的示例中,它将每个元音替换为 X。

function replaceWithRegex(str, regex, replaceWith) {
  return str.replace(regex, replaceWith);
}

replaceWithRegex('HEllo there', /[aeiou]/gi, 'X'); //"HXllX thXrX"

Just an alternative suggestion: when you find yourself reaching for "case insensitive regex", you can usually accomplish the same by just manipulating the case of the strings you are comparing:只是一个替代建议:当您发现自己正在使用“不区分大小写的正则表达式”时,您通常可以通过操作您正在比较的字符串的大小写来完成相同的操作:

const foo = 'HellO, WoRlD!';
const isFoo = 'hello, world!';
return foo.toLowerCase() === isFoo.toLowerCase();

I would also call this easier to read and grok the author's intent!我也会称这更容易阅读和理解作者的意图!

For example to search word date , upper or lowercase you need to add param i例如要搜索单词date ,大写或小写,您需要添加参数i

i = means incasesensitive i = 表示不区分大小写

example例子

const value = "some text with dAtE";
/date/i.test(value)

or或者

const value = "some text with dAtE";
 new RegExp("/date/","i");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM