用js正则表达式 123456790 转成1 2 3 4 5 67 90
您可以使用JavaScript的正则表达式和字符串操作来实现这个转换过程。以下是一种可能的解决方案:
const str = '1:2,3:4,5:6,7:90';
// 用正则表达式匹配键值对
const regex = /(\d+):(\d+)/g;
const matches = str.matchAll(regex);
// 将匹配到的键值对转换为对象的属性和值
let result = {};
for (const match of matches) {
const key = match[1];
const value = match[2];
result[key] = value;
}
// 将对象转换为字符串
const output = JSON.stringify(result);
console.log(output);
输出结果为:{"1":"2","3":"4","5":"6","7":"90"}
这个解决方案首先使用正则表达式 (\d+):(\d+) 来匹配字符串中的键值对。然后,使用 matchAll() 方法来获取所有匹配结果的迭代器。接下来,使用 for...of 循环遍历匹配结果,并将键值对转换为对象的属性和值。最后,使用 JSON.stringify() 方法将对象转换为字符串
原文地址: https://www.cveoy.top/t/topic/hTM7 著作权归作者所有。请勿转载和采集!