简体   繁体   English

如何将字符串(包含位置)转换为数组

[英]How to convert string (containing location) to an array

I have a string which contains location: 我有一个包含位置的字符串:

var string = "[ 30.733315, 76.77941799999999,City,6,10/28/2013 10:28:39 AM]"

How to convert this to an array, so that i can get 如何将其转换为数组,以便我可以

arr[0] = 30.733315,
arr[1] = 76.77941799999999 so on.

String.split() is not working here. String.split()在这里不起作用。

Split on [ , ] and , . [],上分割。

] must be escaped in the split regex ]必须在分割正则表达式中转义

var arr = string.split(/[[,\]]/).filter(function(el) { return el.trim(); })

Array.prototype.filter is required to remove empty strings from the array. 需要Array.prototype.filter才能从数组中删除空字符串。

A more readable version of filter would be: filter可读性更高的版本是:

arr.filter(function(el) {
  return el.trim().length === 0;
});
var string = "[ 30.733315, 76.77941799999999,City,6,10/28/2013 10:28:39 AM]";
string = string.replace('[',"['");
string = string.replace(']',"']");
string = string.replace(',',"','","gi");

console.log(string);
arr=eval(string);

console.log(arr);

Try this 尝试这个

var mystring= "[ 30.733315, 76.77941799999999,City,6,10/28/2013 10:28:39 AM]"
var list = mystring.split(',');

Output: 输出:

for(var i = 0; i < list.length; i++)
{
  alert(list[i]);
}

String.split Splits a String object into an array of strings by separating the string into substrings. String.split通过将字符串对象拆分为子字符串,将String对象拆分为字符串数组。

A cross-browser solution: 跨浏览器解决方案:

var string = "[ 30.733315, 76.77941799999999,City,6,10/28/2013 10:28:39 AM]";

var arr = string.replace(/\[|\]/g,'')
                .replace(/ /g,'')
                .split(',');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM