JavaScript正则表达式忽略大小写 [英] JavaScript Regex Ignore Case

查看:193
本文介绍了JavaScript正则表达式忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配字符串的一部分,它应该不区分大小写。我有以下代码,但我从来没有得到替换的字符串。

I am trying to match a part of the string and it should be NOT case sensitive. I have the following code but I never get the replaced string.

var name = 'Mohammad Azam'
var result = name.replace('/' + searchText + '/gi', "<b>" + searchText + "</b>");

searchText变量将是moha或mo或moh。

The searchText variable will be "moha" or "mo" or "moh".

如何以粗体标签获取匹配的内容。

How can I get the matching thing in bold tags.

推荐答案

/ pattern /具有含义当它作为文字输入时,而不是像你那样构造字符串。 (我不是100%肯定。)

/pattern/ has meaning when it's put in as a literal, not if you construct string like that. (I am not 100% sure on that.)

尝试

var name = 'Mohammad Azam';
var searchText = 'moha';
var result = name.replace(new RegExp('(' + searchText + ')', 'gi'), "<b>$1</b>");
//result is <b>Moha</b>mmad Azam

编辑:

添加了上述代码的演示页面。

Added the demo page for the above code.

Demo→

代码

这篇关于JavaScript正则表达式忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆