简体   繁体   English

Javascript 正则表达式匹配特定字符串

[英]Javascript Regex to match specific string

I need help with my javascript code.我需要有关我的 javascript 代码的帮助。

        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".它的作用基本上是将“rd”替换为“road”,将“st”替换为“street”。 How can I make it so that it should replace only the exact word?我怎样才能使它只替换确切的单词?

For example.例如。 If its Verdana Rd.如果它的Verdana Rd。 it should result in Verdana Road它应该导致 Verdana Road

My current code, it results in Veroadana Road.我当前的代码,它导致 Veroadana Road。

A straightforward way is to add \b in your Regex:一种简单的方法是在您的正则表达式中添加\b

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.不相关,但是当您将输入显式转换为小写时,output 也将完全小写。 A slight improvement would be to apply the lower case only when you do the lookup in the object:仅当您在 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:如果您还想保持要替换的单词的首字母大写,那么您需要在回调 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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