1

I just found that the jquery trim function (using 1.8.x) will not trim Japanese whitespaces. Any better solution to this issue?

PaulusHub
  • 385
  • 1
  • 4
  • 17

2 Answers2

1

I wrote something after reading this:

https://github.com/jquery/jquery/pull/896

DEMO

$.extend({
  jTrim: function(str){
    var re = /^[\s\xA0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]+|[\s\xA0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]+$/g 
    return str.replace(re,"");
  }
});

console.log(">"+$.jTrim(' よろしくお願い申し上げます。')+"<");
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Thanks you. I found the problem is actually a browser-based. Jquery trim works fine in IE9, but I had to support IE >= 6 :( – PaulusHub Feb 27 '13 at 23:42
1

For an ES5 shim including a (supposedly) complete implementation of the ES5 String.trim() method, see https://github.com/kriskowal/es5-shim

// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
    "\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
    // http://blog.stevenlevithan.com/archives/faster-trim-javascript
    // http://perfectionkills.com/whitespace-deviations/
    ws = "[" + ws + "]";
    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
        trimEndRegexp = new RegExp(ws + ws + "*$");
    String.prototype.trim = function trim() {
        if (this === undefined || this === null) {
            throw new TypeError("can't convert "+this+" to object");
        }
        return String(this)
            .replace(trimBeginRegexp, "")
            .replace(trimEndRegexp, "");
    };
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Dave Methvin
  • 1,458
  • 10
  • 12