2012-12-04 184 views

回答

2
var str = ' that is image'; 
str.replace(/^\s+|\s+$/g,""); //Removes left and right extra spaces 
+0

也許只是使用正則表達式的前半部分,因爲他們似乎只想刪除前導空格。否則,如果瀏覽器本身不支持'trim',我總是將其用作polyfill – Ian

3

的JavaScript 1.8以後有一個trim()功能。見MDN

你可以使用這樣的:

var str = " that is an image "; 
alert(str.trim());//"that is an image"; 

由於MDN介紹,以確保充分的支持,你可以添加這樣的原型方法:

if(!String.prototype.trim) { 
    String.prototype.trim = function() { 
    return this.replace(/^\s+|\s+$/g,''); 
    }; 
} 
+0

以前從未聽說過'trim()',謝謝! –

1
var str = ' that is image'; 
str = str.replace(/\s/g,""); 
console.log(str); 
alert(str); 
+0

正確的想法,但我不認爲他們實際上使用'_'字符,因爲他們指定了「空格」,並且正在使用它來顯示它們表示空間區域的位置。 – Ian