3

如何在 javascript 中通过替换将值替换为数组。

我想一起替换数字(例如)。如何?

1-替换白衣-> 11
2-替换白衣->22

演示:http: //jsfiddle.net/ygxfy/

<script type="text/javascript">
    var array = {"1":"11", "2":"22"}
    var str="13332";
    document.write(str.replace(array));
</script>​
4

5 回答 5

5

您必须使用 RegEx 创建一个模式,然后将其传递给该.replace方法。

var array = {"1":"11", "2":"22"}; // <-- Not an array btw.
// Output. Example: "1133322"
document.write( special_replace("13332", array) );

function special_replace(string_input, obj_replace_dictionary) {
    // Construct a RegEx from the dictionary
    var pattern = [];
    for (var name in obj_replace_dictionary) {
        if (obj_replace_dictionary.hasOwnProperty(name)) {
            // Escape characters
            pattern.push(name.replace(/([[^$.|?*+(){}\\])/g, '\\$1'));
        }
    }

    // Concatenate keys, and create a Regular expression:
    pattern = new RegExp( pattern.join('|'), 'g' );

    // Call String.replace with a regex, and function argument.
    return string_input.replace(pattern, function(match) {
        return obj_replace_dictionary[match];
    });
}
于 2012-04-06T14:52:13.837 回答
3

http://jsfiddle.net/mendesjuan/uHUs9/

您可以将函数传递给replace方法

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

String.prototype.mapReplace = function (replacements) {
    var regex = [];

    for (var prop in replacements) {
        regex.push(RegExp.escape(prop));
    }

    regex = new RegExp( regex.join('|'), "g" );

    return this.replace(regex, function(match){
      return map[match];
    });
}


var map = {"1":"11", "2":"22"};    
var str="13332";

document.write(str.mapReplace(map));​
于 2012-04-06T15:00:30.267 回答
1
var str = "13332",
    map = {"1":"11", "2":"22"};

str.split("").map( function(num ){
    return map.hasOwnProperty(num) ? map[num] : num;
}).join("");

//"1133322"
于 2012-04-06T15:05:32.303 回答
0
<script type="text/javascript">
    var rep = {"1":"11", "2":"22"}
    var str="13332";

    for (key in rep) {
        str = str.split(key).join(rep[key]);
    }

    document.write(str);
</script>​
于 2012-04-06T14:51:08.893 回答
0

使用reduce函数呢?

<script type="text/javascript">
  var array = {"1":"11", "2":"22"};
  var str = "13332";

  str = Object.keys(array).reduce(function(result, key) {
    return result.replace(new RegExp(key, 'g'), array[key]);
  }, str);

  document.write(str);
</script>
于 2017-07-14T21:08:27.670 回答