JavaScript String

By | October 15, 2013

JavaScript String 本身是沒有 trim function,但透過簡單 regular expression 便可做到:

String.prototype.ltrim = function(){
return this.replace(/(^\s*)/g, “”);
}

String.prototype.rtrim = function(){
return this.replace(/(\s*$)/g, “”);
}

String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, “”);
}

還有這個用來測試是否 ASCII 也很實用:

String.prototype.isAscii = function() {
return !/[\u0080-\uFFFF]/.test(this);
}