<CharlieDigital/> Programming, Politics, and uhh…pineapples

13Jul/10Off

HTML-ifying Text in SharePoint

This has probably been done to death, but here's my version of how to "HTML-ify" HTML text in SharePoint calculated fields into rendered HTML using jQuery:

var htmlPattern = /[^<]*<([^ ]+)[^<]+<\/\1>.*/;
var ltPattern = /&lt;/g;
var gtPattern = /&gt;/g;
 
$(selectors).each(function(index, item){
    var html = $(item).html().replace(ltPattern, "<").replace(gtPattern, ">");

    if(!htmlPattern.test(html)) { return; }

    $(item).html(html);
});

Perhaps the most interesting part of this script is the regular expression used to capture the HTML tag. Unlike other versions I've seen, it easily handles any HTML tag and will match-and-replace even elements that don't start and end with HTML tags (your content can have leading and trailing text or other HTML). This is exceedingly useful if your calculated field contains textual content or if you need to HTML-ify some string that is rendered in say the newsletter list style.

Specify your selectors wisely to minimize the number of elements to scan.

Here it is again in a "best practices" format hooked up to a simple namespace:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Sample HTMLIFY </title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// Create a simple namespace.
var my = {};

// Define the util class.
function util() {
var htmlPattern = /[^<]*<([^ ]+)[^<]+<\/\1>.*/;
var ltPattern = /&lt;/g;
var gtPattern = /&gt;/g;

return {
// The main function which takes a set of jQuery selectors.
htmlify: function(selectors) {

$(selectors).each(function(index, item){
var html = $(item).html()
.replace(ltPattern, "<")
.replace(gtPattern, ">");

if(!htmlPattern.test(html)) { return; }

$(item).html(html);
});
}
}
}

// Instantiate the object.
my.util = new util();

// Convert to rendered HTML
$(document).ready(function() {
my.util.htmlify(".text1, .text2");
});
</script>
</head>

<body>
<div class="text1">This is some HTML text &lt;a href=""&gt;a link&lt;/a&gt;</div>
<div class="text2">This is some HTML text &lt;a href=""&gt;a link&lt;/a&gt;
<span style="background:green">This text is in a span</span></div>
<div class="text2">This is some HTML text &lt;span style="background:red"&gt;some text&lt;/span&gt;</div>
</body>
</html>

You should be able to copy/paste that and run it.

Posted by Charles Chen

Filed under: Dev, SharePoint Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.