使 Javascript 正则表达式不区分大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9833419/
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
Make Javascript regular expression case insensitive
提问by Adam
I'm using a jquery function I found to find words in a div and highlight them. I'm using this along with a search tool so the case is not always going to match the words exactly. How can I convert this to make it case insensitive?
我正在使用我发现的 jquery 函数在 div 中查找单词并突出显示它们。我将它与搜索工具一起使用,因此案例并不总是与单词完全匹配。如何转换它以使其不区分大小写?
$.fn.highlight = function(what,spanClass) {
return this.each(function(){
var container = this,
content = container.innerHTML,
pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
replaceWith = '<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '"></span>',
highlighted = content.replace(pattern,replaceWith);
container.innerHTML = highlighted;
});
}
回答by Joseph
pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi')
add the 'i' flagto make it case insensitive
添加“i”标志以使其不区分大小写
回答by jjm
Just add the 'i' flag.
只需添加 'i' 标志。
pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi')
回答by Zed
$.fn.highlight = function(what,spanClass) {
return this.each(function(){
var container = this,
content = container.innerHTML,
pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi'),
replaceWith = '<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '"></span>',
highlighted = content.replace(pattern,replaceWith);
container.innerHTML = highlighted;
});
}
}
回答by j08691
Just add "i":
只需添加“我”:
pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi'),
From MDN:
来自MDN:
Regular expressions have four optional flags that allow for global and case insensitive searching. To indicate a global search, use the g flag. To indicate a case-insensitive search, use the i flag. To indicate a multi-line search, use the m flag. To perform a "sticky" search, that matches starting at the current position in the target string, use the y flag. These flags can be used separately or together in any order, and are included as part of the regular expression.
正则表达式有四个可选标志,允许进行全局和不区分大小写的搜索。要指示全局搜索,请使用 g 标志。要指示不区分大小写的搜索,请使用 i 标志。要指示多行搜索,请使用 m 标志。要执行“粘性”搜索,匹配从目标字符串中的当前位置开始,请使用 y 标志。这些标志可以单独使用或以任何顺序一起使用,并作为正则表达式的一部分包含在内。