2015-04-24 65 views
0

我使用Tree Walker方法獲取node列表document。我的源就像是以下幾點:如何獲得文本節點內字符串的起始偏移量?

var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT); 
//treeWalker.currentNode = [set the starting node]; 
while (treeWalker.nextNode()){ 
    var presentNode = treeWalker.currentNode; 
    if(presentNode.nodeType === 3 && presentNode.nodeValue.replace(/^\s+|\s+$/g, '')){ 
     //Getting here present node value.  
    } 
} 

假設presentNode值是我在JavaScript的新手。 我需要起始偏移量和結束偏移量新手字符串。 如何在javascript中獲取這些值?任何人都可以支持我?

回答

1

您可以使用indexOflength

var positionOfNovice = "I am novice in javascript.".indexOf('novice'); 
 
var novicePos = { 
 
    start: positionOfNovice, 
 
    end: positionOfNovice + 'novice'.length 
 
}; 
 

 

 
var result = document.querySelector('#result'); 
 
result.innerHTML = 
 
    'String: "I am novice in javascript."\n\nPosition of "novice": \n' + 
 
    JSON.stringify(novicePos, null, ' '); 
 

 
// more generic: create a String extension: 
 
String.prototype.getWord = getWord; 
 

 
result.innerHTML += 
 
    '\n\nUsing extension:\n' + 
 
    JSON.stringify("I am novice in javascript.".getWord('novice'), null, ' '); 
 

 
function getWord(word) { 
 
    var pos = this.indexOf(word); 
 
    return { 
 
     string: this, 
 
     word: word + (pos < 0 ? ' NOT FOUND' : ''), 
 
     startPosition: pos > -1 ? pos : null, 
 
     endPosition: pos > -1 ? pos + word.length : null 
 
    } 
 
}
<pre id="result"></pre>

相關問題