Javascript 正则表达式删除双空格时出现问题

Javascript 正则表达式删除双空格时出现问题,javascript,regex,Javascript,Regex,我使用了简单的JavaScript正则表达式来删除双空格: 例如 为此,我使用了这个函数。但它不起作用 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(/

我使用了简单的JavaScript正则表达式来删除双空格:

例如

为此,我使用了这个函数。但它不起作用

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.
}

你唯一的问题是这一行的双重标准:

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

第二次替换时,您有一个开括号。

您的问题不清楚,请说明您的问题。我需要删除双重声明>我正在使用笔记本电脑。>我在用我的笔记本电脑。因为我写了这个正则表达式,它不起作用。在这里,或者在原始代码中,双开参数也是一个输入错误吗?@jswolf:它不仅仅对空格起作用。除alpha、空格、圆点和连字符外的其他字符都很好。
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));