Monday, January 11, 2016

Highlight UTF text in Javascript

How can I highlight text in a page which contains non-english text?

Javascript regexp do not support such text at all.  It is planned to be supported at ECMAScript6, which currently, May-2015, is not supported by any-browser\node.js, but there are build tools to mimic it`s functionality.


How to highlight in Angular? using filters  

The solution is from this link, and a filter-tutorial is here.

1. Assuming you have a style like:
       .highlighted { background: yellow }

2. Create a filter
angular.module('moduleName,[])
.filter('highlight', function($sce) {
    return function(text, phrase) {
      if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
        '<span class="highlighted">$1</span>')
        return $sce.trustAsHtml(text)
  }
    })

3. In the html, Instead of using the regular binding:
{ model.test-text | highlight}
make sure to use the ng-bind-html
<ANY ng-bind-html="model.test-text | highlight"></ANY>




No comments: