0

I have a string that contains coordinates and some whitesace:

E.G. "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:

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

What's the most performant way to perform this transformation in JavaScript?

1
  • 1
    Check out the answer I posted. It should be exactly what you needed. I updated the previous answer so it would do what you asked. Commented May 13, 2014 at 18:48

1 Answer 1

2

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(","));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.