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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3939715/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:44:18  来源:igfitidea点击:

Case insensitive regex in JavaScript

javascriptregex

提问by Amit

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. Here is what I am doing:

我想使用 JavaScript 从我的 URL 中提取查询字符串,并且我想对查询字符串名称进行不区分大小写的比较。这是我在做什么:

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>/ibut it did not help. Any idea how can that be achieved?

但是上面的代码做了区分大小写的搜索。我试过了,/<regex>/i但没有帮助。知道如何实现吗?

回答by Micha? Niklas

You can add 'i' modifier that means "ignore case"

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

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

回答by Brad Mace

modifiers are given as the second parameter:

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

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

回答by Diego Fortes

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"