开发者

Problem with regex to remove double spaces

I have used simple JavaScript regex to remove double space:

Eg.

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

for that I used this function. but its nt working.

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


Your only problem is the double (( in this line:

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

After that, everything works.

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.


this works just fine

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

you had an open parenthesis on the second replace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜