| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Monday, January 26, 2009

Javascript Trim For SharePoint

Over the course of my Javascripting for SharePoint, I've found a lot of peculiarities with how SharePoint codes it's pages for the different browsers. Syntax that should work regardless of browser doesn't because SharePoint writes the page differently. Sometimes a space is written " " and sometimes it's " ". When you're writing code that relies on character counts or other triggers, this can cause problems.

To complicate the matter, Javascript doesn't have a trim() function, so I built one. On the grand scale, it's not that amazing of an accomplishment, plenty of other folks already have done this, but I wanted to dabble with RegEx and develop something in a vaccume that I could compare to get an idea for how my own problem solving stacks up against the rest.

Here's what I came up with:
function trim(x)
{
x = x.replace(/(^\t)(\t*)/,"").replace(/(\t*)(\t$)/,""); // tabs
x = x.replace(/(^\n)(\n*)/,"").replace(/(\n*)(\n$)/,""); // new lines
x = x.replace(/(^\r)(\r*)/,"").replace(/(\r*)(\r$)/,""); // return characters
x = x.replace(/(^<br>)(<br>*)/,"").replace(/(<br>*)(<br>$)/,""); // html returns
x = x.replace(/(^ )( *)/,"").replace(/( *)( $)/,""); // spaces
x = x.replace(/(^&nbsp;)(&nbsp;*)/,"").replace(/(&nbsp;*)(&nbsp;$)/,""); // html spaces
return x;
}
To make this work, just add it somewhere in your code and when you want to use it, just call =)
...
strTrimmed = trim(strNotTrimmed);
...
document.write(trim(strWhatever));
...
if (strBlargh == trim(strHonk))
...

0 comments: