0

I have a Function that gets a number and highlight that word number from a sentence.

The sentence would be in Persian and Right To Left. All words are separated by "|" in the sentence.

I'm using Arrays, because other common methods do not work on RTL texts, including the replace method in this post: How to highlight text using javascript

The problem is when the words are highlighted, there is an extra space after each word, which I don't need that to be highlighted.

I want to eliminate that, please.

I have prepared a demo in here: https://liveweave.com/vp6YQi

function hilWrd(i) {
  var txt1 = document.getElementById( "RTL1" ).innerHTML;
  var txt2 = document.getElementById( "RTL2" );
  var ary = txt1.split("|");

  ary.splice( i-1, 0, "<span class='hil'>" );
  ary.splice( i-1 + 2, 0, "</span>" );
  txt2.innerHTML = ary.join(" ");  
}

expected result: to highlight "تست" actual result: it highlights "تست "

Divar Yab
  • 127
  • 1
  • 1
  • 7

1 Answers1

2

Instead of increasing the number of array elements, just wrap the word inside that particular array element:

ary[i-1] = "<span class='hil'>" + ary[i-1] + "</span>";

Demo - Link

Sunil Kashyap
  • 2,946
  • 2
  • 15
  • 31
trincot
  • 317,000
  • 35
  • 244
  • 286