Hala El Barchah Hala El Barchah - 3 months ago 19
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) {
if(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)
}
}
})

.highlighted{
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">
<label>search</label>
<input ng-model="searchString"/>
<div ng-if="!searchString">{{content}}</div>
<div ng-if="searchString" ng-bind-html="content | highlight:searchString"></div>

</div>
</div>




Answer

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>')
Comments