How do you display the first set of characters of a Publishing Page in a display template?
Display templates
I like the usage of Display templates but every now and then there are problems that should be easy to solve that are not. Well, the problem in this article is actually one of those easily solved problems. Once you know how.
I’ve got a page in my Office 365 SharePoint online environment. I’m using the page content field to collect the article content.
So in my Display Template I’m adding PublishingPageContentOWSHTML
<mso:ManagedPropertyMapping msdt:dt=”string”>’PublishingPageContentOWSHTML’:’PublishingPageContentOWSHTML'</mso:ManagedPropertyMapping>
Then within the JavaScript section of the display template I’m collecting the summary:
var summary = ctx.CurrentItem.PublishingPageContentOWSHTML;
and I’ve got my html code in the summary variable. If I now get the substring of the summary to get my first 100 characters I might end up with a bit of a mess and most likely nowhere near 100 characters.
“<p>Today we have launched the new intranet …. </p><p><span class=\”ms-rteStyle-Normal\”>Lorem ipsum”
Within my display template I’m including some html to display the summary
_#= summary =#_
This will now appear in SharePoint as:

So now the solution.
first I’m creating a div element
var tag = document.createElement(‘div’);
Then I’m setting the innerHTML of the div that I just created
tag.innerHTML = ctx.CurrentItem.PublishingPageContentOWSHTML;
first set of characters of a Publishing Page
And now the big trick. Set my summary variable to the innerText
var summary = tag.innerText.substring(0,100) + “… “;
So all together this gives me:
var tag = document.createElement(‘div’);
tag.innerHTML = ctx.CurrentItem.PublishingPageContentOWSHTML;
var summary = tag.innerText.substring(0,100) + “… “;
And SharePoint now displays the full first 100 characters:

Interesting. I’ve used regex to remove the html tags and then gave a substring in what became. I did this so that if there is a link in the content does not break my layout
Hi Pedro, That is also an option. In my case I’m looking at quite simple html content
Useful. Thanks for your help!