Home > Blockchain >  Make default double click behavior treat zero width spaces as word characters
Make default double click behavior treat zero width spaces as word characters

Time:10-28

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?

CodePudding user response:

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>

CodePudding user response:

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/>

CodePudding user response:

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 >Try <u>s​e​l​e​c​t​i​n​g</u> the underlined word.</p>

<p ></p>

  • Related