简体   繁体   English

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

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

I am using Tree walker approach to get node list of document . 我正在使用Tree walker方法来获取document node列表。 My source is like following: 我的资料如下:

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.      
    }
}

Suppose presentNode Value is I am novice in javascript. 假设presentNode值是我是javascript新手。 I need start offset and end offset of novice string. 我需要新手字符串的开始偏移和结束偏移。 How can I get these values in javascript? 如何在javascript中获取这些值? Can anyone support me? 谁能支持我?

You can use indexOf and length : 您可以使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM