正则表达式删除双空格的问题

问题描述:

我已经使用简单的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

你唯一的问题是在这条线的双重((

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. 

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)); 

你不得不在第二替换左括号这工作得很好。