0

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.

M14
  • 1,780
  • 2
  • 14
  • 31
  • _I would like to get the first charactor of html_ i guess you forgot to add this in the question. Have you tried anything? We don't know what? Where? – Jai Nov 30 '15 at 12:21
  • http://stackoverflow.com/questions/33978281/how-to-httputility-htmldecode-in-javascript/33978327#33978327 – potatopeelings Nov 30 '15 at 12:22
  • can you add controller code too in-order to know your real problem because I tried normally then I got the expected output.If you would share your full code it will be easy to sort out the problem with same approach. – Dark Army Nov 30 '15 at 12:29
  • "the starting and ending tags are un predictable". I think the question is not properly asked OP donot wants the the first letter – Dark Army Nov 30 '15 at 12:46

3 Answers3

1

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

David Votrubec
  • 3,968
  • 3
  • 33
  • 44
  • @Jai Yes, I know. And what? The function only uses dom fragment, it was never appended to the real DOM, so this is imho perfectly OK even in Angular – David Votrubec Nov 30 '15 at 12:32
  • 1
    @Jai it could cause problems only when run outside of browser environment ... which I do not expect – David Votrubec Nov 30 '15 at 12:34
1

You can remove HTML tags and simply access first letter as we do in an array like this.

var regex = /(<([^>]+)>)/ig
,   body = "<p><span>hii my content</span></p>"
,   result = body.replace(regex, "");
console.log(result[0]);

Using jQuery

console.log($('<p><span>hii my content</span></p>').text()[0]);

It will give you "h"

Jay Shukla
  • 5,794
  • 8
  • 33
  • 63
1

if your contet

<p class="first-letter"><span>hii my content</span></p>

then

$(".first-letter").text().substring(0,1)

would return you the first letter no matter how many levels of nesting are there within the class .first-letter

Rovi
  • 259
  • 1
  • 3