如何修剪JavaScript中的字符串? git
不知道什麼錯誤能夠隱藏在這裏,可是我用這個: github
var some_string_with_extra_spaces=" goes here " console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
或者,若是文本包含輸入: 瀏覽器
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
另外一種嘗試: app
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
我有一個使用trim的庫。 所以經過使用如下代碼解決了它。 this
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
使用本機JavaScript方法: String.trimLeft()
, String.trimRight()
和String.trim()
。 es5
IE9 +和全部其餘主要瀏覽器均支持String.trim()
: spa
' Hello '.trim() //-> 'Hello'
String.trimLeft()
和String.trimRight()
是非標準的,但除IE以外的全部主要瀏覽器均支持 prototype
' Hello '.trimLeft() //-> 'Hello ' ' Hello '.trimRight() //-> ' Hello'
使用polyfill能夠輕鬆實現IE支持: code
if (!''.trimLeft) { String.prototype.trimLeft = function() { return this.replace(/^\s+/,''); }; String.prototype.trimRight = function() { return this.replace(/\s+$/,''); }; if (!''.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } }
String.prototype.trim = String.prototype.trim || function () { return this.replace(/^\s+|\s+$/g, ""); }; String.prototype.trimLeft = String.prototype.trimLeft || function () { return this.replace(/^\s+/, ""); }; String.prototype.trimRight = String.prototype.trimRight || function () { return this.replace(/\s+$/, ""); }; String.prototype.trimFull = String.prototype.trimFull || function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " "); };
從Matt Duereg無恥地偷走了。 ip
對於IE9 +和其餘瀏覽器
function trim(text) { return (text == null) ? '' : ''.trim.call(text); }