我有额外的空格字符字符串。每次有一个以上的空白,我希望它是只有一个。我如何使用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();
其他回答
如果你想限制用户在名字中给空格,只需创建一个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, ' ') )
你可以扩充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/
这个怎么样?
“我的测试字符串\t\t与疯狂的东西很酷”。替换(/\s{2,9999}|\t/g, ' ')
输出"my test string with crazy stuff is cool "
这个也可以去掉任何标签