Javascript多次搜索新的位置变量

时间:2012-05-27 21:57:55

标签: javascript arrays position match

我有以下文字:

var text= 
    "The sad sad man uses a bat to swing the bats 
    away from his sad garden .
    Sadly he doesn't succeed. "

假设我想搜索单词"sad"

var match;
re = /sad/g,
    match;
while (match = re.exec(text)) {
    console.log(match); 
match.poz = ....
}

如何让match.poz成为像[line,position on the collumn]一样的元组(数组),所有这些都是从0,0开始的?

例如

  • 1场比赛 - > match.poz = [0,4]
  • 2匹配 - > match.poz = [0,8]
  • 3匹配 - > match.poz = [1,14]
  • 4匹配 - > match.poz = [2,0]

2 个答案:

答案 0 :(得分:1)

我能够构建一个简单的解析器,而不是使用正则表达式,我认为这是不可能的(没有很多帮助)来获得Javascript中的位置。所有这一切都是通过这一行,一次一个字符,并向前“窥视”以查看当前位置是否提供sad\n

var text = "The sad sad man uses a bat to swing the bats \naway from his sad garden .\nSadly he doesn't succeed.",
    length = text.length,
    matches = [],
    lines = 0,
    pos = 0;

for (var i = 0; i < length; i++){
    var word = text.substring(i, i + 3).toLowerCase();

    if (word == 'sad') {
        matches[matches.length] = [lines, pos];
    }

    if (word.indexOf('\n') == 0) {
        lines++;
        pos = 0;
    } else {
        pos++;
    }
}

console.log(matches);

在Firebug控制台中给出了以下内容:

[[0, 4], [0, 8], [1, 14], [2, 0]]

http://jsfiddle.net/Zx5CK/1/

答案 1 :(得分:0)

首先,我认为您需要能够以某种方式划分线条。可能在输入数据中使用某些字符(例如'\ n')。 然后解决问题的一种方法是使用split函数将每行中的单词作为数组。然后,您可以编写一个函数,该函数接收一行和所需的单词,并将每个单词与您要搜索的单词进行比较。

 //where i denotes the currently read line.
 var indexInLine = checkforWordInLine(input.line[i].split(' '), "sad");
 if(indexInLine != -1) 
 //word found in line. 
 // save indexInLine and 'i', the line index      


 function checkforWordInLine(line, searchKey)
 {
    var wordIndex = -1;
   for(var i=0,j=line.length; i < j; i++)
   {
      if(line[i] === searchKey)
      wordIndex = i;
   }
   return wordIndex;
 }
相关问题