最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace many values in a string based on searchreplace pairs - Stack Overflow

programmeradmin0浏览0评论

How can replace values as array by replace in javascript.

I want done replace numbers (for example) together. how is it?

1 -replace whit-> 11
2 -replace whit-> 22

DEMO: /

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

How can replace values as array by replace in javascript.

I want done replace numbers (for example) together. how is it?

1 -replace whit-> 11
2 -replace whit-> 22

DEMO: http://jsfiddle/ygxfy/

<script type="text/javascript">
    var array = {"1":"11", "2":"22"}
    var str="13332";
    document.write(str.replace(array));
</script>​
Share Improve this question edited Apr 6, 2012 at 15:14 Phrogz 304k113 gold badges667 silver badges757 bronze badges asked Apr 6, 2012 at 14:48 jennifer Joliejennifer Jolie 7276 gold badges16 silver badges31 bronze badges 2
  • But there is no array... – xdazz Commented Apr 6, 2012 at 14:51
  • 1 That is not an array, that is a variable named "array" that is referencing an object. Note also that it is just about never appropriate to use document.write(). – Phrogz Commented Apr 6, 2012 at 14:51
Add a ment  | 

5 Answers 5

Reset to default 5

You have to create a pattern, using a RegEx, and then pass it to the .replace method.

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

http://jsfiddle/mendesjuan/uHUs9/

You can pass a function into the replace method

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));​
var str = "13332",
    map = {"1":"11", "2":"22"};

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

//"1133322"
<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>​

What about using reduce function ?

<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>
发布评论

评论列表(0)

  1. 暂无评论