首页 > 解决方案 > 在 JavaScript 中将字符串拆分为列表

问题描述

如何将以下 SVG 'd' 字符串拆分为对象列表

input = "M 13.09765625 -4.82421875 L 107 -4.82421875" 

output = [
         ['M', 13.097, -4.824], // values are float and 3 decimal long
         ['L', 107, -4.824]
         ]
input = "M 68.609375 130.265625 
         L 175.87890625 130.265625
         C 175.87890625 130.265625 111.0706329345703 197.2464141845703 175.87890625 262.0546875
         L 68.609375 130.265625
         Z"

output = [['M', 68.609375, 130.265625],
         ['L', 175.87890625, 130.265625],
         ['C', 175.87890625, 130.265625, 111.0706329345703, 197.2464141845703, 175.87890625, 262.0546875],
         ['L', 68.609375, 130.265625],
         ['Z']"

我的方法是这样的,需要更多的调整

    path = "M 13.09765625 -4.82421875 L 107 -4.82421875";
    path = path.replace(/M/g, "\nM");
    path = path.replace(/L/g, "\nL");
    path = path.trim().split("\n");

    let segments = [];

    path.forEach(function (p, i) {
        segments.push(p.trim().split(" "));
    });

标签: javascriptarraysstringlistsplit

解决方案


这是一种描述完整匹配并具有捕获组以隔离您想要的部分的正则表达式方法。

.exec()在一个循环中使用,它将null在第一次失败时返回。

const input = "M 13.09765625 -4.82421875 L 107 -4.82421875";

const re = /([ML]) (-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)/g
let match = null;
const result = [];

while ((match = re.exec(input))) {
  result.push(match.slice(1));
}

console.log(result);


推荐阅读