0

I am trying to search a word which is initial caps but matchCase search option is not working as expected. below is my code :

textToHighlight = "Deed";
var rangeCol = para.search(textToHighlight, { matchCase: true});

Paragraph Text : Seller shall convey title to the Property to Buyer by grant deed in the form of letter("Deed").

It always returns first instance of deed which is non caps.

Thanks

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
Manohar
  • 31
  • 1
  • 6

1 Answers1

0

See the snippet below, it's working as expected. Are you trying to do something else?

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

In terms of highlighting the text with vanilla JavaScript, I've come up with the following:

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>
Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67
  • Thanks for your reply Luis! problem is when I try to select that returned range which highlights first instance, not the actual instance which is initial caps ''' rangeCol.items[winstance].select(); ''' – Manohar Apr 13 '20 at 07:54
  • Could you please share your highlighting code? I think the problem is not with `search()` – Luís Ramalho Apr 13 '20 at 07:57
  • `typeof rangeCol === "number"`, you cannot do `rangeCol.items[winstance].select();` – Luís Ramalho Apr 13 '20 at 07:58
  • ' var rangeCol = para.search(textToHighlight, { matchCase: true }); para.context.load(rangeCol); return para.context.sync().then(function () { rangeCol.items[winstance].font.color = 'blue'; rangeCol.items[winstance].select(); para.context.sync().then(function () { q.resolve(); }) }) ' – Manohar Apr 13 '20 at 08:03
  • here, winstance = 0 because it has only one Deed which is initial caps – Manohar Apr 13 '20 at 08:08