简体   繁体   中英

Javascript Regex to match specific string

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM