2014-05-07 66 views
-4

我使用了以下內容:如何刪除所有空格?

var xpto = "AB23. 3434-.34212 23 42." 

我刪除 「」 「 - 」和「」

xpto.replace(/\./g,"").replace(/\-/g,"").replace("/\s/g","") 

如何刪除所有空格?

+1

爲空白的正則表達式是'\ s' –

+2

'替換( 「/ \ S/G」 ,「」)'=/='替換(/ \ s/g,「」)' – h2ooooooo

回答

4

您最近的replace正在使用字符串,而不是正則表達式。您也似乎並沒有一直保持結果:

xpto = xpto.replace(/\./g,"").replace(/\-/g,"").replace(/\s/g,""); 
// ^ No quotes here -------------------------------^--^ 
// \--- Remember result 

您也可以縮短這一點,只需調用replace一次,使用字符類([...]):

xpto = xpto.replace(/[-.\s]/g,""); 

(注意使用時-字符字面類在字符類中,您必須使其成爲開幕後的第一個字符[或結尾]前的最後一個字符,或者在其前面加上反斜線。 racters([a-z],例如),它的意思是「範圍內的任何字符」。)

+3

'.'不需要在角色類中逃脫。 –

+0

@NiettheDarkAbsol:好的,謝謝。 –

1

可以使用replace功能

xpto.replace(/\s/g,''); 
1

你的錯誤來自周圍的最後一個正則表達式的報價,但是去掉空格我還要指出的是,你在呼喚replace比需要更多的方式:

xpto = xpto.replace(/[\s.-]/g,""); 

這將去掉空格,點和連字符。

1

你做得對,但忘了引號""/\s/g。此外,您想要將字符串xpto更改爲替換的xpto,以便現在可以對其執行某些操作。

的Javascript

var xpto = "AB23. 3434-.34212 23 42." 
xpto = xpto.replace(/\./g,"").replace(/\-/g,"").replace(/\s/g,""); 

輸出

AB233434342122342

JSFiddle demo