在字符串javascript中找到标记的位置

时间:2015-06-20 07:02:42

标签: javascript jquery html regex string-matching

提前致谢。我遇到了问题。我有一个像这样的字符串

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";

我想知道字符串中每次出现span标记的位置。在示例字符串中,我在第3个单词之后有一个span标记,在第9个单词之后有一个span标记,在第12个单词之后有一个。所以结果数组将是[3,9,12]。请帮帮我。

编辑:另外,除了上面的数组之外,我能否在每个span标签内包含多少个单词?

4 个答案:

答案 0 :(得分:2)

您可以使用以下正则表达式检查字符串:

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";
var regex = /<span>/gi, result, indices = [];
while ((result = regex.exec(string))) {
     console.log(result.index);
}

这将打印标记<span>的每个位置。您可以调整While代码,它应该完成其余的工作。 : - )

答案 1 :(得分:2)

正如您标记了javascript / jQuery,一种方法是使用.each()split()

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";

//Count position
var pos = [];
string.split(' ').forEach(function(val,i){
    if(val.indexOf('<span>') > -1){
        pos.push(i)
    }
});

//Count words inside each  `<span>`
var wordCount = $('<div/>').html(string).find('span').map(function(){
    return this.innerText.split(' ').length
})
console.log(wordCount)

<强> Demo

答案 2 :(得分:2)

您可以使用:

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";

var arr = string.split(/[\s>]+/);

var posn = [];
for(var p=-1; (p=arr.indexOf('<span', p+1)) >= 0; )
   posn.push(p)

//=> [3, 10, 14]

答案 3 :(得分:1)

我认为你正在寻找这个

var string = "This is where <span>I got stuck</span> and I am <span>clueless</span> can anyone <span>help please</span> ";

var prevPos = 0;

var pos = [];
var words = [];
string.split(' ').forEach(function(val,i){
    if(val.indexOf('<span>') > -1){
        pos.push(i);
        var wordsCount = i - prevPos;
        prevPos = i; 
        words.push(wordsCount);

    }
});

console.log(pos);
console.log(words);