我有额外的空格字符字符串。每次有一个以上的空白,我希望它是只有一个。我如何使用JavaScript做到这一点?
当前回答
就像这样:
Var s = " a b c "; console.log ( s.replace(/\s+/g, ' ') )
其他回答
jQuery.trim()工作得很好。
http://api.jquery.com/jQuery.trim/
就像这样:
Var s = " a b c "; console.log ( s.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 word word。字,字,字'; //使用ES5: s = s.split (' ') .filter (n (n){返回函数 != '' }).加入(' '); console.log(年代);// "a b word word. "词,词,词" //或ES2015: S = S .split(' ')。Filter (n => n).join(' '); console.log(年代);// "a b word word. "词,词,词"
甚至可以用.filter(String)替换filter(n => n)
它用空格分隔字符串,从数组中删除所有空数组项(超过一个空格的数组项),并将所有单词再次连接到一个字符串中,在它们之间使用一个空格。
我假定您希望从字符串的开头和/或结尾删除空格(而不是删除所有空格?
如果是这样的话,你需要一个像这样的正则表达式:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
这将删除字符串开头或结尾的所有空格。如果你只想从结尾开始修剪空格,那么正则表达式应该是这样的:
mystring = mystring.replace(/\s+$/g,' ');
希望这能有所帮助。