1

I'm writing a mapper which spots identifying words in a string and replaces them with another word. In my case a location identifier with the actual directory location.


My Problem is on line 8 : str.replace(x.toString(), keys[x]);

The value x is the value as expected but keys[x] returns undefined.

var keys = {
   "$processes"        : "/processes",
   "$local_resources"  : "/feeds/local"
};

function CoreRoute(str){
   for (var x in keys){
      str.replace(x, keys[x]);
   }
   return str;
}

I am developing in the node enviroenment. But I'm pretty sure it's a mistake with my logic.

1 Answer 1

1

Strings are immutable in Javascript, so String.replace() can't modify str, it returns a new String with the replacement performed. Change

str.replace(x, keys[x]);

to

str = str.replace(x, keys[x]);

End code:

var keys = {
    "$processes"       : "/processes",
    "$local_resources" : "/feeds/local"
};

function CoreRoute(str) {
    for (var x in keys) {
        str = str.replace(x, keys[x]);
    }
    return str;
}
Sign up to request clarification or add additional context in comments.

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.