3

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.net/ygxfy/

<script type="text/javascript">
    var array = {"1":"11", "2":"22"}
    var str="13332";
    document.write(str.replace(array));
</script>​
2
  • But there is no array... 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(). Commented Apr 6, 2012 at 14:51

5 Answers 5

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];
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Very nice. It might be even nicer if you (or the OP :) wrapped this up as a reusable function.
@Phrogz I've turned the thing in a re-usable function. Also omitted Object.keys, since I had to loop through the keys anyway.
Very nice. Any reason you used /(...)/,'$1' instead of /.../,'$&'?
@Phrogz Because I've written the RegEx escaping method a while back, without considering $&. $& does also work.
3

http://jsfiddle.net/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));​

2 Comments

This is a good js regex primer. I Might try to use the esajilla for this use case as a simpler implementation.
Small mistake in function String.prototype.mapReplace : map is not defined. replacements should be used instead of map (or renamed to map).
1
var str = "13332",
    map = {"1":"11", "2":"22"};

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

//"1133322"

2 Comments

@JuanMendes "23333" is the result using that map, is that not the expected result? Also, using that map with "123" results in "233", so please try the code before shaming it ;P
How to make this work for variable length to-be-replaced patterns?
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>​

5 Comments

@spacevillain Did you try this?
I did and I don't get what is wrong with it. 1 gets replaced by 11, and 2 by 22, resulting in 1133322
For non-repeated keys, and non-modified prototypes, this method is sufficient. However, when keys may interfere with each other, a problem arises. Example: 1-2, 2-3 on 123 becomes 333 instead of 233 (the 1 is replaced with 2, then with 3).
@RobW I think the argument about modified prototype is a different one. Not everyone wants to use hasOwnProperty in their for in loops if they've made a decision not to use libs that modify Object.prototype. Discussions about that should not spill into every example that uses for in
@JuanMendes I only mentioned the prototype for completeness. The biggest issue is that the whole string is used for the replacement, which may lead to unexpected results (as shown in the simple example in my comment).
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.