I am trying to extract the X and Y coordinates of the top-right & bottom-left of a text box given the value of the bound.
Example: [84,672][1356,889]
Is there a quick and easy function available in JavaScript that would extract the above values into two separate variables so that I can then calculate the center coordinates? Like:
A = [84,672]
B = [1356,889]
CodePudding user response:
You can use a RegEx:
const input = "[84,672][1356,889]";
// parse input
const nums = input.match(/\d /g).map(Number);
const A = [nums[0], nums[1]];
const B = [nums[2], nums[3]];
console.log(A, B);
// calculate midpoint
const mdpt = [(A[0] B[0])/2, (A[1] B[1])/2];
console.log(mdpt);
CodePudding user response:
There is no quick and simple single function that will do that, no. But you can use simple string functions to make your own:
Here I used substring
, indexOf
, replace
, and split
.
As the result was an array, I used map
to convert the original strings to numbers, and destructuring assignment to get the results.
const input = "[84,672][1356,889]";
function extractCoordinates(input) {
// get a and b as strings using indexOf with offset
const aStr = input.substring(0, input.indexOf('[', 1));
const bStr = input.substring(input.indexOf('[', 1), input.length);
// create a function that will remove the brackets and coerce to a number
const mapToNumber = (s) => s.replace(/\[|\]/g, '');
// split the strings on the comma and run the function on the parts
const a = aStr.split(',').map(mapToNumber);
const b = bStr.split(',').map(mapToNumber);
// And that's it
return [a, b];
}
// Here I use array destructuring to get the results:
const [a, b] = extractCoordinates(input);
console.log(a, b);
CodePudding user response:
Another option is to convert your string into a valid JSON string so that:
"[84,672][1356,889]"
becomes
"[[84,672],[1356,889]]"
You can do this by replacing ][
with ], [
and wrapping your string in[]
. Then you can parse this string into a JavaScript array, and use indexing to extract the values into variables:
const A = arr[0];
const B = arr[1];
Or you can use destructuring assignment as shown below to extract the nested arrays into variables
const str = "[84,672][1356,889]";
const [A, B] = JSON.parse(`[${str.replaceAll("][", "],[")}]`);
console.log(A);
console.log(B);
Note: If you can't support replaceAll()
, you can use a global regular expression with the .replace()
method instead: .replace(/]\[/g, '],[')