[英]JavaScript Regex Ignore Case
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>");
The searchText variable will be "moha" or "mo" or "moh". searchText变量将是“moha”或“mo”或“moh”。
How can I get the matching thing in bold tags. 如何以粗体标签获取匹配的内容。
/pattern/ has meaning when it's put in as a literal, not if you construct string like that. / pattern /在它作为文字输入时有意义,而不是像你那样构造字符串。 (I am not 100% sure on that.)
(我不是百分百肯定的。)
Try 尝试
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
EDIT: 编辑:
Added the demo page for the above code. 添加了上述代码的演示页面。
I think you're looking for new RegExp, which creates a dynamic regular expression - what you're trying to do now is match a string ( not a regexp object ) : 我想你正在寻找新的RegExp,它创建了一个动态的正则表达式 - 你现在要做的就是匹配一个字符串(不是正则表达式对象):
var name = 'Mohammad Azam', searchText='moha';
var result = name.replace(new RegExp(searchText, 'gi'), "" + searchText + ""); result
EDIT: Actually, this is probably what you were looking for, nevermind ^ 编辑:实际上,这可能是你正在寻找的,没关系^
var name = 'Mohammad Azam', searchText='moha';
name.match( new RegExp( searchText , 'gi' ) )[0]
name // "Moha"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.