如何在从逗号分隔的文本文件中读取的行中创建子字符串
How to create sub string in a line read from text file separated by comma
我是 java 脚本新手,我有一个这样的文本文件 Address.txt :
Andhra Pradesh,East Godavari,Reach within 36 Hrs
Andhra Pradesh,Guntur,Reach within 36 Hrs
Andhra Pradesh,Krishna,Reach within 36 Hrs
Andhra Pradesh,Visakhapatnam,Reach within 36 Hrs
Andhra Pradesh,Chittoor,Reach within 36 Hrs
现在我想用逗号分隔每个子字符串,因此会有 3 个子字符串。必须存储在三个数组中。
如何在 Javascript 中做到这一点假设我阅读此文件的方式是:
$.ajax({
type: 'GET',
url: 'Address.txt',
dataType: 'text',
}).success(function (test)
{
alert('inside ajax : '+test);//lets say this show aall the data of test file
var col1 = [];
var col2 = [];
var col3 = [];
var j = 0;
//How to concert them in substring and save in these tree columns ?
for (var i = 0; i <= test.length - 3; i = i + 3)
{
}
})
你应该使用:
var array = string.split(',');
split函数会根据逗号分割字符串,得到var array
中的数组。
对您提到的三个字符串中的每一个使用上述逻辑,并根据需要将其存储在 cols 中。
使用str.split()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
所以首先我们需要在换行符 \n
上拆分以获得所有行。然后对于每一行,我们在逗号 ,
字符上拆分以获得三个子字符串中的每一个,如您所说。
这是一个冗长但简单的方法:
var lines = test.split('\n');
for (var i = 0; i < lines.length; i++) {
var cols = lines[i].split(',');
col1.push(cols[0]);
col2.push(cols[1]);
col3.push(cols[2]);
}
所以对于每一行,我们将第一个子字符串添加到 col1
数组,第二个子字符串添加到 col2
数组,等等
查看此 google 脚本以将任何 CSV 文件转换为数组或对象
http://jquery-csv.googlecode.com/git/examples/basic-usage.html
我是 java 脚本新手,我有一个这样的文本文件 Address.txt :
Andhra Pradesh,East Godavari,Reach within 36 Hrs
Andhra Pradesh,Guntur,Reach within 36 Hrs
Andhra Pradesh,Krishna,Reach within 36 Hrs
Andhra Pradesh,Visakhapatnam,Reach within 36 Hrs
Andhra Pradesh,Chittoor,Reach within 36 Hrs
现在我想用逗号分隔每个子字符串,因此会有 3 个子字符串。必须存储在三个数组中。
如何在 Javascript 中做到这一点假设我阅读此文件的方式是:
$.ajax({
type: 'GET',
url: 'Address.txt',
dataType: 'text',
}).success(function (test)
{
alert('inside ajax : '+test);//lets say this show aall the data of test file
var col1 = [];
var col2 = [];
var col3 = [];
var j = 0;
//How to concert them in substring and save in these tree columns ?
for (var i = 0; i <= test.length - 3; i = i + 3)
{
}
})
你应该使用:
var array = string.split(',');
split函数会根据逗号分割字符串,得到var array
中的数组。
对您提到的三个字符串中的每一个使用上述逻辑,并根据需要将其存储在 cols 中。
使用str.split()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
所以首先我们需要在换行符 \n
上拆分以获得所有行。然后对于每一行,我们在逗号 ,
字符上拆分以获得三个子字符串中的每一个,如您所说。
这是一个冗长但简单的方法:
var lines = test.split('\n');
for (var i = 0; i < lines.length; i++) {
var cols = lines[i].split(',');
col1.push(cols[0]);
col2.push(cols[1]);
col3.push(cols[2]);
}
所以对于每一行,我们将第一个子字符串添加到 col1
数组,第二个子字符串添加到 col2
数组,等等
查看此 google 脚本以将任何 CSV 文件转换为数组或对象
http://jquery-csv.googlecode.com/git/examples/basic-usage.html