gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:16:32 24 4
gpt4 key购买 nike

我正在使用树遍历器方法来获取文档节点列表。我的来源如下:

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>

关于javascript - 如何获取文本节点内字符串的起始偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29840275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com