2011-08-26 86 views
0

我已經使用簡單的JavaScript正則表達式來刪除雙空間:正則表達式刪除雙空格的問題

例如,

" I am       working on my Laptop. " 
as 
"I am working on my laptop." 

因爲我使用了這個功能。但它的工作。

function valid(f) 
{ 
    f.value = f.value.replace(/[^a-zA-Z\s.'-,]/gixsm, ''); 
    f.value = f.value.replace((/\s+/g, ' '); //remove more than 2 white spaces spaces. 
    f.value = f.value.replace(/^\s+|\s+$/g, ''); //remove spaces of before new line. 
} 
+1

你的問題不清楚,請說明你的問題。 –

+0

我需要刪除雙重聲明 >「我正在使用我的筆記本電腦。」 >「我正在使用我的筆記本電腦。」 因爲我寫這個正則表達式,它不工作。 – Aditii

+1

是在這裏或在原始代碼中的雙打開paren錯字嗎? – jswolf19

回答

0

你唯一的問題是在這條線的雙重((

f.value.replace((/\s+/g, ' '); 

在那之後,一切正常。

var f = {}; 
f.value = " I am       working on my Laptop. " 

function valid(f) 
{ 
    f.value = f.value.replace(/[^a-zA-Z\s.'-,]/gixsm, ''); 
    // notice the single paren here! 
    f.value = f.value.replace(/\s+/g, ' '); 
    f.value = f.value.replace(/^\s+|\s+$/g, ''); 
} 
valid(f) 
console.log(f.value) // I am working on my laptop. 
0

var string = " I am       working on my Laptop. "; 
function valid(f) 
{ 
    f = f.replace(/[^a-zA-Z\s.'-,]/gixsm, ''); 
    f = f.replace(/\s+/g, ' '); //remove more than 2 white spaces spaces. 
    f = f.replace(/^\s+|\s+$/g, ''); //remove spaces of before new line. 
    return f; 
} 

document.write(valid(string)); 

你不得不在第二替換左括號這工作得很好。