js正则 101202 转成101 202
你可以使用正则表达式的 exec 方法来实现这个转换:
const str = '101:202';
const regex = /(\d+):(\d+)/;
const match = regex.exec(str);
const result = { [match[1]]: parseInt(match[2]) };
console.log(result); // 输出 { 101: 202 }
这里的正则表达式 /(\d+):(\d+)/ 匹配了两个数字之间的冒号,并使用括号将这两个数字分组。然后使用 exec 方法在字符串中找到匹配的内容,并通过数组的索引将匹配的数字取出来。最后,我们将这两个数字组成一个对象,其中第一个数字作为属性名,第二个数字通过 parseInt 函数转换为整数后作为属性值。
原文地址: https://www.cveoy.top/t/topic/hTMN 著作权归作者所有。请勿转载和采集!