Search code examples
javascriptjqueryangularjsangular-filters

ng-bind-html get first letter of html content


I am having a situation where i am using ng-bind-html for html binding. I would like to get the first charactor of html content excluding the html tags. Below is my sample code.

<span class="first-letter">{{firstLetter}}</span>
            <div id="myDiv" ng-CLoak data-ng-bind-html="trustAsHtml(data.ContentDescription)" class="{{currentFont}}"></div>

my html string would look like following

<p><span>hii my content</span></p>
the starting and ending tags are un predictable.

i would like to get first letter "h" not "<" Thanks in advance.


Solution

  • You can let the browser strip html for you using the textContent property

    function strip(html)
    {
       var tmp = document.createElement("DIV");
       tmp.innerHTML = html;
       return tmp.textContent || tmp.innerText || "";
    }
    

    and since you are interested only in that first letter, than you probably don't need the ng-bind-html :)

    In case you want to highlight that first letter, then use CSS :first-letter https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3Afirst-letter