我有一个ID列表,我试图使用JavaScript split()函数将其分开。每个ID的格式如下:
格式示例
(51.87,0.2125) // Lat and Long values with comma separation
(48.87,0.3130)在JavaScript中,这些ID都存储在字符串中的值属性中。
示例:
(48.87,0.3130),(51.87,0.2125),(48.87,0.3130),(51.87,0.2125)我的目标是在结束括号和逗号之后使用拆分函数。如何在考虑结束括号和逗号的情况下使用拆分函数?
目前,我有以下几点:
var location_id = $(this).find("input").val().split(',');期望输出
["(48.87,0.3130)","(51.87,0.2125)","(48.87,0.3130)","(51.87,0.2125)"]发布于 2018-02-08 17:03:16
您可以使用正则表达式/\(\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))
发布于 2018-02-08 17:03:17
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);
发布于 2018-02-08 17:04:04
见内嵌评论:
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);
https://stackoverflow.com/questions/48690817
复制相似问题