javascript - 在 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(" "));
});
解决方案
这是一种描述完整匹配并具有捕获组以隔离您想要的部分的正则表达式方法。
它.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);
推荐阅读
- linux - inotifywait 未在 bash 脚本中执行 while 循环
- aws-lambda - 来自 AWS Lambda 的 RDS 中的 SQL 死锁
- javascript - 为什么 fetch 在我的移动浏览器上不起作用?
- android - 有没有办法在应用程序被杀死时接收数据通知?
- python-2.7 - 循环遍历 OrderedDict 对象错误
- c++ - 为什么 std::is_aggregate
聚合? - ionic-framework - 如何在非英语(德语)ionic 3 应用程序中显示和读取浮点数?
- x86 - MSROM 程序中的条件跳转指令?
- timezone - Elixir - Timex 检测英国夏令时的开始和结束时间
- python - 如何在 if 语句中使用 JSON 文件中的值