JavaScript中如何使用regex按'.index.'规则拆分字符串
JavaScript 基于正则拆分字符串实现方案
直接使用匹配.index.格式的正则作为split方法的入参即可完成需求:
// 示例字符串 const targetStr = 'publication_or_portfolio_links.0.link'; // 拆分逻辑:匹配前后带点的一个或多个数字段 const splitResult = targetStr.split(/\.\d+\./); console.log(splitResult); // 输出:["publication_or_portfolio_links", "link"]
正则规则说明
\.:转义匹配字面量点号,规避正则中点号匹配任意字符的特殊语义\d+:匹配1个及以上的数字,兼容索引值大于9的场景(例如.15.、.124.均可正常匹配)
容错增强版本
如果需要适配更复杂的输入场景(比如拆分后后半段还有点号、输入无匹配的数字段等),可以用封装后的方法:
function splitPathByIndex(path) { const parts = path.split(/\.\d+\./); // 保证返回长度为2的数组,后半段如果有多个点号也会完整保留 return parts.length >= 2 ? [parts[0], parts.slice(1).join('.')] : [path, '']; } // 测试用例 console.log(splitPathByIndex('user.3.profile.avatar.url')); // 输出:["user", "profile.avatar.url"] console.log(splitPathByIndex('normal_string_without_index')); // 输出:["normal_string_without_index", ""]
内容的提问来源于stack exchange,提问作者Naveed Ali
相关产品推荐
相关产品推荐

