0

I am trying to make multiple replacements to a string (php variable) using javascript. This code:

<script>
jQuery(document).ready(function() {
var map = {
    "2014": "",
    "2015": "",
    "2016": "",
    "-": " ",
    "ú": "u"
};

var str = "<?php echo $data; ?>";
var result = str.replace(/[<?php echo $data; ?>]/g, function(m) {
    return replacements[m];
});
jQuery('.even_data').html(result);
});
</script>

Gives me the error:

invalid range in character class
var result = str.replace(/[2014-08-28]/g, function(m) {
                         ^

An alternative will be to use:

jQuery(document).ready(function() {
  var str = "<?php echo $data; ?>";
  var result = str.replace('2014','');
  jQuery('.even_data').html(result);
});

But how can you make multiple replacements?

Thanks!

I tried these answers but they did not work: Javascript str_replace many at once

Community
  • 1
  • 1
Claudiu Creanga
  • 8,031
  • 10
  • 71
  • 110

5 Answers5

1

In Javascript Regex, the brackets [] are special characters that define character classes. If you want to use them as literals you have to escape them:

str.replace(/\[2014-08-28\]/g, function(m) {
Stryner
  • 7,288
  • 3
  • 18
  • 18
1

It's much easier to make PHP do this instead of JavaScript.

$map = array(
    "2014" => "",
    "2015" => "",
    "2016" => "",
    "-" => " ",
    "ú" => "u"
);

$data = '2014-08-28';
$data = str_replace(array_keys($map), array_values($map), $data);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

You can use

function multiReplace(str, map) {
    for(var i in map) if(map.hasOwnProperty(i)) {
        str = str.replace(
            new RegExp(i.replace(/[.^$*+?()[{\\|]/g, '\\$&'), 'g'),
            map[i]
        );
    }
    return str;
}
var result = multiReplace(str, map);

It works like this:

  1. It iterates all own properties of map
  2. It builds a proper regex for each property
    1. First, it escapes special regex characters: .^$*+?()[{\|
    2. Then it uses that string to build a global (g flag) regex
  3. It replaces all matches of that regex with the corresponding value in map
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

DEMO

Your regular expression is no good. After replacing it with an actual RE it should work:

    var result = str.replace(/(\d{4}|-|ú)/g, function(m) {
        return map[m];
    });
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

Using JS it would be smth like that:

var str = "2014 12 03, 2014, day";
var map = {"2014" : "2012", 
       "12" : "a",
       "03" : "",
       "day" : "sfsdf"};
$.each(map, function(key, value) {
    str = str.replace(new RegExp(key ,"g"), value);
});

//new str: "2012 a , 2012, sfsdf"

neli
  • 149
  • 5