programmer-in-training Posted March 22, 2008 Share Posted March 22, 2008 Hello,I have worked with JavaScript for a long time, but I have never come across this before. In the JavaScript replace() Method, it says that the first string literal should be /Example/ instead of "Example". Where did that come from? I read the tutorial, but I didn't see anything about that kind of string literal.Anyway, to do a global case-insensitive search (which is what I need to do, and I don't want to re-invent the wheel), it says I must do this: /Example/gi. That's fine, but Example is a literal. How do I make it do that with a variable? Everything I try fails. I need to make the global insensitive version of this: r = r.replace(initials[n][0], initials[n][1]); Thanks,programmer-in-training Link to comment Share on other sites More sharing options...
justsomeguy Posted March 22, 2008 Share Posted March 22, 2008 I believe the slashes are a shortcut to create a RegExp object:http://www.w3schools.com/jsref/jsref_obj_regexp.aspYou should be able to do that manually. var re = new RegExp();re.compile(initials[n][0], "gi");r = r.replace(re, initials[n][1]); Jhecht probably has a better way, the w3schools reference doesn't include the constructor. Link to comment Share on other sites More sharing options...
jhecht Posted March 22, 2008 Share Posted March 22, 2008 You would do something like this: var userCheck = prompt("Look For?");if(userCheck!=null || userCheck !=undefined){ var regex = new RegExp(userCheck,"ig"); alert(regex);} That will output something like "/programmer/ig", assuming i put programming in as the prompt value; Link to comment Share on other sites More sharing options...
Jesdisciple Posted March 22, 2008 Share Posted March 22, 2008 http://www.regular-expressions.info/javascript.html further explains how to use the constructor, and http://www.w3schools.com/jsref/jsref_obj_regexp.asp also has some useful info. Link to comment Share on other sites More sharing options...
programmer-in-training Posted March 22, 2008 Author Share Posted March 22, 2008 It works perfectly! Thank you. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.