如何匹配前后紧邻字母的数字 实现JS地址文本首字母大写
你当前的正则仅匹配字符串开头、或空格后的首个字符,没有覆盖数字后紧邻字母的场景,调整正则即可解决。
调整后完整代码
const input = "2a smith road "; const input2 = "333 flathead lake road, apartment 3b"; // 调整后的格式化方法 const formatAddress = (str) => str.replace(/(^\w)|(\s+\w)|(?<=\d)\w/g, letter => letter.toUpperCase()).trim(); console.log(formatAddress(input)) // 输出:2A Smith Road console.log(formatAddress(input2)) // 输出:333 Flathead Lake Road, Apartment 3B
正则规则说明
^\w:匹配整个字符串开头的首个字符\s+\w:匹配1个或多个空白字符后的首个字符(?<=\d)\w:使用后行断言,匹配前面紧邻数字的字符,覆盖数字+小写字母的大写转换需求
如果需要兼容不支持后行断言的旧JS运行环境,可以用以下兼容写法:
const formatAddress = (str) => str.replace(/(^\w|\s+\w|\d\w)/g, match => { return match.length === 2 ? match[0] + match[1].toUpperCase() : match.toUpperCase(); }).trim();
内容的提问来源于stack exchange,提问作者Herby Osbourne
相关产品推荐
相关产品推荐

