我正在尝试搜索一个初始大写的单词,但 matchCase 搜索选项未按预期工作。下面是我的代码:
textToHighlight = "Deed";
var rangeCol = para.search(textToHighlight, { matchCase: true});
段落文本:卖方应通过授予契约以信函(“契约”)的形式将财产所有权转让给买方。
它总是返回非上限的第一个契约实例。
谢谢
我正在尝试搜索一个初始大写的单词,但 matchCase 搜索选项未按预期工作。下面是我的代码:
textToHighlight = "Deed";
var rangeCol = para.search(textToHighlight, { matchCase: true});
段落文本:卖方应通过授予契约以信函(“契约”)的形式将财产所有权转让给买方。
它总是返回非上限的第一个契约实例。
谢谢
请参阅下面的代码段,它按预期工作。你在尝试做其他事情吗?
let para = "[...] to Buyer by grant deed in the form of letter"
textToHighlight = "Deed";
var rangeCol = para.search(textToHighlight, { matchCase: true});
console.log(rangeCol); // -1, not found
para = "[...] to Buyer by grant Deed in the form of letter"
textToHighlight = "Deed";
var rangeCol = para.search(textToHighlight, { matchCase: true});
console.log(rangeCol); // 24, found
在使用原生 JavaScript 突出显示文本方面,我提出了以下建议:
let _text = text.innerText;
button.addEventListener("click", () => {
text.innerText = _text;
let textToHighlight = input.value;
var rangeCol = text.innerText.search(textToHighlight, {
matchCase: true,
});
let node = text.childNodes[0];
let spaces = node.textContent.match(/^\s*/)[0].length;
let range = new Range();
range.setStart(node, spaces + rangeCol);
range.setEnd(node, spaces + rangeCol + textToHighlight.length);
const mark = document.createElement("mark");
range.surroundContents(mark);
});
#text {
margin: 10px 0;
}
mark {
background-color: yellow;
}
<div id="text">
Seller shall convey title to the Property to Buyer by grant deed in the form of letter("Deed").
</div>
<input id="input" type="text" />
<button id="button">Highlight</button>