我使用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中获取这些值?任何人都可以支持我吗?
答案 0 :(得分:1)
您可以使用indexOf
和length
:
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>