0

I need help with my javascript code.

        var mapObj = {
          rd:"road",
          st:"street",
        };
        var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
        package_street_name = package_street_name.toLowerCase().replace(re, function(matched){
          return mapObj[matched];
        });

What it does basically replace "rd" with "road", and "st" with "street". How can I make it so that it should replace only the exact word?

For example. If its Verdana Rd. it should result in Verdana Road

My current code, it results in Veroadana Road.

1 Answer 1

1

A straightforward way is to add \b in your Regex:

new RegExp("\\b(" + Object.keys(mapObj).join("|") + ")\\b", "gi");

Unrelated, but as you explicitly convert the input to lower case, the output will also be completely lower case. A slight improvement would be to apply the lower case only when you do the lookup in the object:

var package_street_name = "Verdana Rd.";
var mapObj = {
    rd:"road",
    st:"street",
};
var re = new RegExp("\\b(" + Object.keys(mapObj).join("|") + ")\\b", "gi");
package_street_name = package_street_name.replace(re, function(matched){
    return mapObj[matched.toLowerCase()];
});

console.log(package_street_name);

If you also want to maintain the capitalisation of the first letter of the word you are replacing, then you need a bit more logic in the callback function:

var package_street_name = "Verdana Rd.";
var mapObj = {
    rd:"road",
    st:"street",
};
var re = new RegExp("\\b(" + Object.keys(mapObj).join("|") + ")\\b", "gi");
package_street_name = package_street_name.replace(re, function(matched) {
    let result = mapObj[matched.toLowerCase()];
    return matched[0] === matched[0].toLowerCase() ? result
        : result[0].toUpperCase() + result.slice(1);
});

console.log(package_street_name);

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.