借助前三个字符在Javascript中查找字符串的索引

时间:2017-02-20 22:32:39

标签: javascript indexof

我有很多tsv文件,每个文件都有标题行。现在标题行中的一个列名是age。在少数文件中,列名称为age,而在其他文件中,它具有EOL字符,例如\r \n

现在我如何使用str.indexOf('age')函数,以便获得年龄索引,而不管列名称年龄与EOL字符如\n\r等等。

敌人例如: tsv file1

Name    Address   Age    Ph_Number

file 2

Name    Address   Age/r

file 3

Name    Address   Age\n

我正在尝试在每个文件标题行中找到age列的索引 但是,当我做 -

header.indexOf('age')

它仅在file1的情况下提供结果,因为在其他2个文件中,ageage\rage\n ..

我的问题是我应该如何在标题行中找到age的索引而不考虑\r \n字符以及age

我现在有以下脚本:

var headers = rows[0].split('\t');
    if (file.name === 'subjects.tsv'){
      for (var i = 0; i < rows.length; i++) {
        var ageIdColumn = headers.indexOf("age");
        console.log(headers)

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,indexOf()返回字符串的起始位置。在它之后发生的事情并不重要:

&#13;
&#13;
var csvFile1 = 'column1,column2,column3,age,c1r1';
var csvFile2 = 'column1,column2,column3,age\r,c1r1';
var csvFile3 = 'column1,column2,column3,age\n,c1r1';

console.log(csvFile1.indexOf("age"));
console.log(csvFile2.indexOf("age"));
console.log(csvFile3.indexOf("age"));
&#13;
&#13;
&#13;

如果您特别想要查找具有特殊字符的版本,请明确查找它们:

&#13;
&#13;
var csvFile4 = 'column1,age\r,column2,column3,age\n,c1r1';
console.log(csvFile4.indexOf("age\r"));
console.log(csvFile4.indexOf("age\n"));
&#13;
&#13;
&#13;

最后,您可能会对确切indexOf()应该做什么感到困惑。它不应该告诉你给定字符串的所有出现位置。它停止照顾第一场比赛。要获得所有位置,您需要一个类似于此的循环:

&#13;
&#13;
var csvFile5 = 'column1,age\r,column2,age, column3,age\n,c1r1';

var results = []; // Found indexes will be stored here.
var pos = null;   // Stores the last index position where "age" was found

while (pos !== -1){
  // store the index where "age" is found 
  // If pos is not null, then we've already found age earlier and we 
  // need to start looking for the next occurence 3 characters after
  // where we found it last time. If pos is null, we haven't found it
  // yet and need to start from the beginning.
  pos = csvFile5.indexOf("age", pos != null ? pos + 3 : pos );
  pos !== -1 ? results.push(pos) : "";
}

// All the positions where "age" was in the string (irrespective of what follows it)
// are recorded in the array:
console.log(results);
&#13;
&#13;
&#13;