non-breaking spaces and jQuery.trim()

Posted: July 28, 2010 in JavaScript

When performing a .trim() function on a string pulled via the .text() tag in jQuery,   will convert into a special space that will not be removed.


<div id="div1">  This is text  </div>

<script type="text/javascript">
jQuery(document).ready(function() {
trimString = jQuery.trim($('#div1').text());

I was able to catch the Unicode character, which ended up being 160, by using:


After performing a regex replace on the string, I was able to achieve a truly trimmed string.

<script type="text/javascript">
$(document).ready(function() {
trimString = $('#div1').text();
var re = new RegExp(String.fromCharCode(160), "g");
trimString = jQuery.trim(trimString.replace(re, " "));
  1. P says:

    How is the code that you have published any different from the native String.trim()? There is no sense in adding library overhead for a native function.

    • Chris says:

      String.trim() will only remove whitespace. While $.trim(string) will remove newlines, spaces, and tabs. It’s also supposed to remove non-breaking spaces, but it appears it relies upon the functionality of the browser’s javascript capabilities. At least it did at time of writing.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s