简体   繁体   English

JavaScript:从字符串中提取坐标

[英]JavaScript: Extract coordinates from a string

I have a string that contains coordinates and some whitesace: 我有一个包含坐标和一些白色的字符串:

EG "SM10,10 50,50 20,10\\nFM10,20 30,40" EG“SM10,10 50,50 20,10 \\ nFM10,20 30,40”

I'd like to extract the list of coordinates: 我想提取坐标列表:

["10,10", "50,50", "20,10", "10,20", "30,40"]

And then perform some transform (let's say scale by 5) and produce a resultant string: 然后执行一些转换(比如说比例为5)并生成一个结果字符串:

"SM50,50 250,250 100,50\nFM50,100 140,200"

What's the most performant way to perform this transformation in JavaScript? 在JavaScript中执行此转换的最高效方法是什么?

Update: 更新:

This should be exactly what you needed. 这应该是你所需要的。 It finds and makes the changes to the coordinates in the string and reassembles the string in the format that it started. 它查找并对字符串中的坐标进行更改,并以其启动的格式重新组合字符串。 Let me know if you think its missing something. 如果你认为它遗漏了什么,请告诉我。

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;
}


Previous answer: 上一个答案:

Here, fast and effective: 在这里,快速有效:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM