1

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); 

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?

Scooter5150
  • 157
  • 2
  • 3
  • 14

2 Answers2

0

See here.

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];
textarea = textarea.replaceArray(find, replace);
Community
  • 1
  • 1
Brij
  • 6,086
  • 9
  • 41
  • 69
0

Here's the dup

function str_replace (search, replace, subject, count) {
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = Object.prototype.toString.call(r) === '[object Array]',
        sa = Object.prototype.toString.call(s) === '[object Array]';
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');

Output >> 'hemmo, mars'

Check this out http://phpjs.org/functions/str_replace:527

Wazy
  • 8,822
  • 10
  • 53
  • 98