2015-06-20 53 views
2

在此先感謝。我遇到了一個問題。我有這樣一個字符串在字符串中找到標籤的位置javascript

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個單詞之後有一個,第12個單詞之後有一個。所以結果數組將會是[3,9,12]。請幫幫我。

編輯另外,除了上面的數組之外,我還可以在每個span標籤內有多少個單詞嗎?

回答

1

正如你所標記的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

+0

嗨...感謝很多人的演示......它說「innertext」是未定義的......用textContent替換它......它工作的很好......非常感謝 – Arumai

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的代碼,它應該完成剩下的工作。 :-)

0

我認爲你正在尋找這個

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); 
+0

很好......謝謝很多...位置數組效果很好...每個span標籤數組中的字數包含錯誤的數字。 [3,6,3]而不是[3,1,2] – Arumai

+0

所以你說的是你需要跨度標籤之間的單詞數量? – Dhaval

+0

是... span標籤內的字數... – Arumai

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] 
相關問題