2

I have an associative array/object such at this:

mymap = {'e':'f', 'l':'g'};

And I want to replace all matching characters in a string using the above as a simple cypher, but only replacing existing characters. As an example,

input = "hello world";
output = input.map(mymap); //how can I do this?
//output is "hfggo worgd"

Balancing performance (for large input) and code size are of interest.


My application is replacing unicode characters with latex strings using this map, but I'm happy to stick with the more general question.

2 Answers 2

2

The following works:

mymap = {'e':'f', 'l':'g'};

var replacechars = function(c){
    return mymap[c] || c;
};

input = "hello world";
output = input.split('').map(replacechars).join('');

although having to split and then join the input seems quite round-about, particularly if this is applied to a wall of text.

Sign up to request clarification or add additional context in comments.

Comments

1

Another way would be loop over the object properties and use regex for each replacement:

var input = 'hello world';
var output = '';

for (var prop in mymap) {
    if (mymap.hasOwnProperty(prop)) {
        var re = new RegExp(prop, 'g');
        output = input.replace(re, mymap[prop]);
    }
}

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.