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


当前回答

你可以扩充String以方法的形式实现这些行为,比如:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

这现在允许你使用以下优雅的形式来生成你想要的字符串:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();

其他回答

jQuery.trim()工作得很好。

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

试试这个。

var string = "         string             1";
string = string.trim().replace(/\s+/g, ' ');

结果将是

string 1

这里发生的事情是,它将首先使用trim()修剪外部空间,然后使用.replace(/\s+/g, ' ')修剪内部空间。

你可以扩充String以方法的形式实现这些行为,比如:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

这现在允许你使用以下优雅的形式来生成你想要的字符串:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();

如果你想限制用户在名字中给空格,只需创建一个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函数。 这是一个按键事件。 初始化一个变量。 给出匹配字符的条件 为匹配的条件显示警报消息。

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

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