admin管理员组文章数量:1188831
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".
How can I get the matching thing in bold tags.
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".
How can I get the matching thing in bold tags.
Share Improve this question edited Jul 27, 2009 at 1:34 azamsharp asked Jul 27, 2009 at 1:24 azamsharpazamsharp 20.1k38 gold badges147 silver badges230 bronze badges 1- What do you want to replace searchText with? Literal string 'searchText' or something else? – SolutionYogi Commented Jul 27, 2009 at 1:29
2 Answers
Reset to default 23/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.)
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.
Demo →
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 ) :
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"
本文标签: JavaScript Regex Ignore CaseStack Overflow
版权声明:本文标题:JavaScript Regex Ignore Case - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738399810a2084712.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论