Hala El Barchah Hala El Barchah - 1 year ago 97
Javascript Question

AngularJS - highlighting part of text causes broken words in non-English language

In the snippet bellow, I'm trying to highlight each part of word that matches the search input in Arabic language, but this makes the letters separate in the text. how can I solve this problem?
try to input

in the field, and you'll see the problem.
I am not good at Regex.

angular.module("myApp", [])
.controller("main", function($scope){
$scope.content="تتيح لك إدارة المستخدمين العديد من الخدمات الأساسية كعرض مستخدمي النظام والتعديل عليها وحذفها.. إضافة إلى عمليات الفلترة عليهابناء على عدة خيارات متاحة "
.filter('highlight', function ($sce) {
return function (text, searchSrting) {
searchSrting = searchSrting.split(/\s+/);
if(typeof text !== "undefined")
for (var i = 0; i < searchSrting.length; i++) {
text = text.replace(new RegExp('(' + searchSrting[i] + ')', 'gi'),
'<span class="highlighted">$1</span>')
return $sce.trustAsHtml(text)

background-color : yellow

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>

<div ng-app="myApp">
<div ng-controller="main">
<input ng-model="searchString"/>
<div ng-if="!searchString">{{content}}</div>
<div ng-if="searchString" ng-bind-html="content | highlight:searchString"></div>


Answer Source

Add a couple of zero-width-joiners before and at the end of your highlight spans to make the characters join up properly:

text = text.replace(new RegExp('(' + searchSrting[i] + ')', 'gi'),
   '&zwj;<span class="highlighted">$1&zwj;</span>')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download