[英]JavaScript: Extract coordinates from a string
我有一個包含坐標和一些白色的字符串:
EG“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(","));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.