我有一个ID列表,我试图使用JavaScript split()函数分开。每个ID都具有以下格式:
格式示例
(51.87,0.2125) // Lat and Long values with comma separation
(48.87,0.3130)
在JavaScript中,这些ID都存储在字符串的value属性中。
示例:
(48.87,0.3130),(51.87,0.2125),(48.87,0.3130),(51.87,0.2125)
我的目标是在结束括号和逗号后使用split函数。如何使用分割函数考虑右括号和逗号?
目前,我有这个:
var location_id = $(this).find("input").val().split(',');
所需输出
["(48.87,0.3130)","(51.87,0.2125)","(48.87,0.3130)","(51.87,0.2125)"]
答案 0 :(得分:1)
您可以使用正则表达式/\(\d+\.\d+,\d+\.\d+\)/g
var str = '(48.87,0.3130),(51.87,0.2125),(48.87,0.3130),(51.87,0.2125)';
console.log(str.match(/\(\d+\.\d+,\d+\.\d+\)/g))
答案 1 :(得分:1)
var data = "(48.87,0.3130),(51.87,0.2125),(48.87,0.3130),(51.87,0.2125)";
// Approach 1
var formattedData = data.split("),").map((el) => {
return el.indexOf(")")==-1 ? el + ")": el;
});
console.log(formattedData);
// Approach 2 (replace , with | and then split using | )
formattedData2 = data.replace(/\),/g, ")|").split("|");
console.log(formattedData2);
答案 2 :(得分:1)
见内联评论:
var s = "(48.87,0.3130),(51.87,0.2125),(48.87,0.3130),(51.87,0.2125)";
var location_id = s.split('),');
location_id.forEach(function(loc, i, ary) {
// Put parens around the value with the left over parens removed
ary[i] = "(" + loc.replace("(","").replace(")", "") + ")";
});
console.log(location_id);
答案 3 :(得分:1)
我能想到的最简单方法是将其拆分为,(
,然后将其映射为删除所有(
和)
,因为第一个和最后一个条目将不一致,然后添加(
和)
重新开始:
const str = '(48.87,0.3130),(51.87,0.2125),(48.87,0.3130),(51.87,0.2125)';
const result = str.split(',(')
.map(x => '(' + x.replace('(','').replace(')','') + ')');
console.log(result);