non-breaking spaces and jQuery.trim()

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.

Example:

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

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

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

alert(trimString.charCodeAt(0));

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, " "));
});
</script>
Advertisements