如何获取文本节点内字符串的起始偏移量?

How can I get start offset of a string inside text node?

我正在使用 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. 我需要 novice 字符串的起始偏移量和结束偏移量。 如何在 javascript 中获取这些值?有人可以支持我吗?

您可以使用 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>