根据搜索/替换对替换字符串中的许多值

jen*_*lie 3 javascript

如何在javascript中替换值替换为数组.

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

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

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

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

Rob*_*b W 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];
    });
}
Run Code Online (Sandbox Code Playgroud)