Jump to content

I need general help with String.replace()


programmer-in-training

Recommended Posts

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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...