【发布时间】:2011-09-04 00:36:10
【问题描述】:
我有带有额外空格的字符串,每次有不止一个空格时,我希望只有一个。
有人吗? 我尝试搜索谷歌,但没有任何对我有用。
谢谢
【问题讨论】:
-
从结尾/开头或文本中的任何位置删除重复的空格?
标签: javascript string trim
我有带有额外空格的字符串,每次有不止一个空格时,我希望只有一个。
有人吗? 我尝试搜索谷歌,但没有任何对我有用。
谢谢
【问题讨论】:
标签: javascript string trim
类似这样的:
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();
【讨论】:
使用带有替换功能的正则表达式可以解决问题:
string.replace(/\s/g, "")
【讨论】:
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
甚至可以将filter(n => n) 替换为.filter(String)
它用 空格 分割字符串,从数组中删除它们所有的空数组项(那些超过一个空格的项),然后将所有单词再次连接成一个字符串,用它们之间有一个空格。
【讨论】:
我想您是要从字符串的开头和/或结尾去除空格(而不是删除 所有 个空格?
如果是这种情况,您将需要这样的正则表达式:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
这将删除字符串开头或结尾的所有空格。如果您只想从末尾修剪空格,则正则表达式将如下所示:
mystring = mystring.replace(/\s+$/g,' ');
希望对您有所帮助。
【讨论】:
'' 而不是 ' '。
jQuery.trim() 效果很好。
【讨论】:
我知道我不应该对某个主题使用死灵法,但考虑到问题的细节,我通常将其扩展为:
为此,我使用这样的代码(第一个正则表达式上的括号只是为了使代码更具可读性...除非您熟悉正则表达式,否则可能会很痛苦):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
这样做的原因是 String-object 上的方法返回一个字符串对象,您可以在该对象上调用另一个方法(就像 jQuery 和其他一些库一样)。如果您想在单个对象上连续执行多个方法,则可以采用更紧凑的编码方式。
【讨论】:
var x = " Test Test Test ".split(" ").join(""); 警报(x);
【讨论】:
试试这个。
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
结果是
string 1
这里发生的事情是它会首先使用trim() 修剪外部空间,然后使用.replace(/\s+/g, ' ') 修剪内部空间。
【讨论】:
这个怎么样?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
输出"my test string with crazy stuff is cool "
这个也去掉了所有标签
【讨论】:
\s 覆盖。不必要的复杂正则表达式,还不如写/\s+/g。
{2,} 的答案。 9999 是不必要的,甚至可能是错误的。我不确定仅匹配和替换 2 个或更多空格对性能有益还是有害。
如果您想限制用户在名称中给出空格,只需创建一个 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;
}
}
});
【讨论】: