简体   繁体   English

不区分大小写的javascript替换考虑到单词边界的正则表达式

[英]Case Insensitive javascript replace regex taking account word boundary

I am writing the replace function in javascript taking account into word boundary 我正在考虑到单词边界的情况下在javascript中编写替换功能

blog = blog.toLowerCase().replace(new RegExp("\\b" + wordList[i].toLowerCase() + "\\b", 'g'), "value to replace");

Now this is a CASE SESITIVE Replace i want to make it CASE INSENSITIVE . 现在这是一个CASE SESITIVE替换,我想使其成为CASE INSENSITIVE

How can i accomplish this? 我怎样才能做到这一点?

Though for Case Insensitive there is \\I but i dont know know how to fit it in my code 虽然对于不区分大小写的用户有\\ I,但我不知道如何将其放入我的代码中

Any help is appreciated. 任何帮助表示赞赏。

Just pass i with g in the flags argument of the new RegExp() constructor . 只需在new RegExp()构造函数flags参数中将g传递给i Like so: 像这样:

new RegExp("\\b" + wordList[i].toLowerCase() + "\\b", 'gi')

At that point, you should be able to remove all the String.toLowerCase calls: 到那时,您应该能够删除所有String.toLowerCase调用:

var re = new RegExp("\\b" + wordList[i] + "\\b", 'gi');
blog = blog.replace(re, 'value to replace');

NB you may need to escape the value of worldList\\[i\\] so that your code does not accidentally try to create a malformed regexp. 注意,您可能需要转义worldList\\[i\\]的值,以便您的代码不会意外地尝试创建格式不正确的正则表达式。

将您的'g'更改为'gi' “ g”表示“全局”,“ i”表示“不区分大小写”:

..., 'gi'), "value...

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

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