我有额外的空格字符字符串。每次有一个以上的空白,我希望它是只有一个。我如何使用JavaScript做到这一点?


当前回答

如果你想限制用户在名字中给空格,只需创建一个If语句并给出条件。就像我一样:

$j('#fragment_key').bind({
    keypress: function(e){
        var key = e.keyCode;
    var character = String.fromCharCode(key); 
    if(character.match( /[' ']/)) {
        alert("Blank space is not allowed in the Name");
        return false;
        }
    }
});

创建一个JQuery函数。 这是一个按键事件。 初始化一个变量。 给出匹配字符的条件 为匹配的条件显示警报消息。

其他回答

var x = "测试测试测试"。分割(" "). join (" "); 警报(x);

使用带有replace函数的正则表达式可以做到这一点:

string.replace(/\s/g, "")

如果你想限制用户在名字中给空格,只需创建一个If语句并给出条件。就像我一样:

$j('#fragment_key').bind({
    keypress: function(e){
        var key = e.keyCode;
    var character = String.fromCharCode(key); 
    if(character.match( /[' ']/)) {
        alert("Blank space is not allowed in the Name");
        return false;
        }
    }
});

创建一个JQuery函数。 这是一个按键事件。 初始化一个变量。 给出匹配字符的条件 为匹配的条件显示警报消息。

就像这样:

Var s = " a b c "; console.log ( s.replace(/\s+/g, ' ') )

jQuery.trim()工作得很好。

http://api.jquery.com/jQuery.trim/