1

I have an html page where some words are split by ​ so they look e.g. like ​​F​Rig​V​M​External​Variable but in the code they are actually F​Rig​V​M​External​Variable​. And the problem is that when I click the word it selects only a part that is bordered by ​ while the desirable behavior is for it to select the whole word

How to override default double click behavior in JS so it would treat ​ not as a word boundary?

wcobalt
  • 312
  • 1
  • 5
  • 17

3 Answers3

1

You can triple-click to select the entire line/paragraph. Otherwise, ​ is a word separator as explained in this question, so the default browser action on double click is to select the word under the cursor.

<!DOCTYPE html>
<html lang='pt-br'>
<head>
<title>Teste</title>
</head>
<body>
a&#8203;better&#8203;test with spaces<br>
a&#8203;better&#8203;test with spaces<br>

</body>
</html>
Niloct
  • 9,491
  • 3
  • 44
  • 57
  • 1
    Thank you for the explanation, but it doesn't answer the question of how to override default double click behavior so it would treat `​` not as a word boundary. Mb the question wasn't stated clearly enough. I'll update it – wcobalt Oct 27 '22 at 17:04
  • Javascript. You can use the `event.detail` property of a `click` event handler to capture double-clicks in this handler. Then you can fiddle with answers like this one: https://stackoverflow.com/a/2838358/152016 but I've failed to create a version that can work with text nodes instead of document ones (meaning you would have to enclose each "word" you would like to join with a tag, and then extend the range with `Range.selectNodeContents`). – Niloct Oct 27 '22 at 17:27
1

I found a solution which preserves the ability for a word to be soft-broken at specific positions but doesn't interfere with selection. It's tag </wbr>. When I replace &#8203; on </wbr> the word can be soft broken at the </wbr>s but when I click any part of a word the whole word gets selected.

F<wbr/>Rig<wbr/>V<wbr/>M<wbr/>External<wbr/>Variable<wbr/>
wcobalt
  • 312
  • 1
  • 5
  • 17
0

If you don't need zero width spaces, you should just remove them using .replace() and the regex flag \u which enables Regex methods to recognize Unicode. The Unicode for a zero width space is: U+200B which in the land of JavaScript is: \u200B.

function noZero(string) {
  return string.replace(/\u200B/gu, '');
}

const str = document.querySelector(".zero").innerHTML;

const result = noZero(str);

document.querySelector(".clean").insertAdjacentHTML("beforeend", result);
<p class="zero">Try <u>s​e​l​e​c​t​i​n​g</u> the underlined word.</p>

<p class="clean"></p>
zer00ne
  • 41,936
  • 6
  • 41
  • 68