• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1238
  • Last Modified:

jquery find / replace arrays?

I'm trying to learning about pattern matching with jQuery and I had a question...

In php, I can do something like this:

$find = array("-", "_", "+");
$replace = array("X", "Y", "Z");

$string = "The alphabet ends in -, _, +";
$newstring = str_replace($find, $replace, $string); 

Open in new window

Which will yield: The alphabet ends in X, Y, Z

Is there a way to accomplish this with jquery?  Where I can define an array of values to search for and replace them with the values in another array?  I get that I can do a replace(/pattern/, "Something"), but was hoping for a way to duplicate this php code in jquery?
2 Solutions
Gurvinder Pal SinghCommented:
Look at below code.
Test Page : http://jsfiddle.net/Kzggk/1/

The plus sign is used in regular expressions to indicate 1 or more characters in a row. So you should use escape

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    var text = "The alphabet ends in -, _, +";
    var array = {"-":"X", "_":"Y", "\\+":"Z"};

    for (var val in array)
      text = text.replace(new RegExp(val, "gi"), array[val]);



Open in new window


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now