如何用JavaScript从Bounds值提取文本框坐标并拆分为独立变量?
提取Bounds坐标的JavaScript简便方法
针对你给出的[84,672][1356,889]这类格式的Bounds值,有几种简便的JavaScript方法可以拆分出两个坐标数组:
方法一:正则表达式匹配
利用正则提取所有被方括号包裹的坐标组,再转换为数字数组:
const bounds = "[84,672][1356,889]"; // 匹配所有[xxx]格式的子串 const coordStrs = bounds.match(/\[(.*?)\]/g); // 转换为数字数组并解构赋值 const [A, B] = coordStrs.map(str => { // 移除首尾方括号,按逗号分割后转数字 return str.slice(1, -1).split(',').map(Number); }); // 此时 A = [84, 672],B = [1356, 889]
方法二:字符串分割与替换
针对固定格式的输入,通过替换分隔符再拆分:
const bounds = "[84,672][1356,889]"; // 将][替换为|,移除首尾方括号后按|分割 const coordParts = bounds.replace('][', '|').slice(1, -1).split('|'); // 转换为数字数组并解构 const [A, B] = coordParts.map(part => part.split(',').map(Number));
后续计算中心坐标示例
拿到A、B两个数组后,直接计算中心坐标:
const centerX = (A[0] + B[0]) / 2; const centerY = (A[1] + B[1]) / 2; console.log(`中心坐标:[${centerX}, ${centerY}]`);
内容的提问来源于stack exchange,提问作者Aritra Nayak
相关产品推荐
相关产品推荐

