1

I want to select a part of a text with JavaScript. I want to specify the range based on length not using nodes. For instance: I have text "AB DDSD" and I want to select from 0-3. I cannot wrap it with an element like span because the Arabic letters do not concatenate.

The following example selects all text inside foo class but how to specify a range for it?

var selection = window.getSelection();
var txt = document.getElementsByClassName("foo");
var range = document.createRange();
range.selectNodeContents(txt);
selection.removeAllRanges();
selection.addRange(range); 

I am open to using other methods instead of select. My goal is to color certain characters in p tag but cannot wrap it using any element. If I wrap only one character of سس then it turns into س س.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

2 Answers2

1

The ligatures are in fact preserved:

let t = document.getElementById('test');
t.innerHTML = `<span style="color: red">${t.textContent.slice(0,3)}</span>${t.textContent.slice(3)}`;
<!DOCTYPE html>
<html>
 <head><meta charset="utf-8"></head>
 <body>
  <span id="test">مرحبا بالعالم</span>
 </body>
</html>

This may have to do with the the font and rendering of your browser, but here's how mine looks:

enter image description here

I don't think adding a zero-width space is the solution considering its purpose.

Rafael
  • 7,605
  • 13
  • 31
  • 46
  • Thanks for the answer. Adding `span` around the text creates a concatenation problem. In your example the text is returns as `مرح با بالعالم` instead of `مرحبا بالعالم` – Maihan Nijat Sep 09 '18 at 23:54
  • I am using Safari that's why it does not concatenate for me. Maybe you are using Chrome or Firefox. The zero-width also does not give a preferred result. – Maihan Nijat Sep 10 '18 at 00:19
  • 1
    I hear your pain, Maihan, it seems that this is still in [draft state](https://www.w3.org/TR/alreq/) – Rafael Sep 10 '18 at 00:30
  • 1
    I have filed a bug at Safari. Hopefully, they'll prioritize it, and get that fixed soon. Please provide your Safari version here. – Rafael Sep 10 '18 at 00:34
0

Found the answer here: Partially colored Arabic word in HTML

Added zero-width character at the end helps: <span>ش&zwj;</span><span>س</span>

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110