我有一个包含坐标和一些空格的字符串:
E.G. “SM10,10 50,50 20,10\nFM10,20 30,40”
我想提取坐标列表:
["10,10", "50,50", "20,10", "10,20", "30,40"]
然后执行一些转换(假设缩放 5)并生成结果字符串:
"SM50,50 250,250 100,50\nFM50,100 140,200"
在 JavaScript 中执行此转换的最高效方法是什么?
最佳答案
更新:
这应该正是您所需要的。它查找并更改字符串中的坐标,并以其开始的格式重新组装字符串。如果您认为它缺少某些内容,请告诉我。
function adjust(input) {
var final = "";
var lastIndex;
var temp = [];
var regex;
var coords = input.match(/\d+,\d+/g);
if (coords) {
for (i = 0; i < coords.length; i++) {
temp = coords[i].split(",");
temp[0] *= 5;
temp[1] *= 5;
regex = new RegExp("([^0-9])?" + coords[i] + "([^0-9])?","g");
regex.exec(input);
lastIndex = parseInt(regex.lastIndex);
final += input.slice(0, lastIndex).replace(regex, "$1" + temp.join(",") + "$2");
input = input.slice(lastIndex, input.length);
temp.length = 0;
}
}
return final + input;
}
上一个答案:
在这里,快速有效:
var coords = "SM10,10 50,50 20,10\nFM10,20 30,40".match(/\d{1,2},\d{1,2}/g);
for (i = 0; i < coords.length; i++) {
var temp = coords[i].split(",");
temp[0] *= 5;
temp[1] *= 5;
coords[i] = temp.join(",");
}
alert (coords.join(","));
关于JavaScript:从字符串中提取坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23636870/