[英]Remove multiple white space between text
var s = "Hello! I'm billy! what's up?"; var result = s.split(" ").join(); console.log(result);
Got this result 得到了这个结果
Hello!,I'm,,billy!,what's,,,,up?
How can i get rid of this annoying extra spaces between string? 我如何摆脱字符串之间的这种烦人的多余空格? So it might look like this.
因此它可能看起来像这样。
Hello!,I'm,billy!,what's,up?
Use a regular expression to find all the spaces throughout the string and rejoin with a single space: 使用正则表达式查找整个字符串中的所有空格,然后以单个空格重新加入:
var s = "Hello! I'm billy! what's up?"; var result = s.split(/\\s+/).join(" "); console.log(result);
You can also do this without using .split()
to return a new array and just use the String.replace()
method. 您也可以不使用
.split()
返回新数组而只使用String.replace()
方法来执行此操作。 The regular expression changes just a little in that case: 在这种情况下,正则表达式仅发生一点变化:
var s = "Hello! I'm billy! what's up?"; var result = s.replace(/ +/g, " "); console.log(result);
You want replace
and \\s+
您要
replace
和\\s+
\\s+
Matches multiple white space character, including space, tab, form feed, line feed.\\s+
匹配多个空格字符,包括空格,制表符,换页符,换行符。
trim
to remove extra white space at the start and end of the stringtrim
以删除字符串开头和结尾的多余空白
var s = " Hello! I'm billy! what's up? "; console.log(s.replace(/\\s+/g, " ").trim());
var s = "Hello! I'm billy! what's up?"; var result = s.replace(/\\s+/g,' ').trim(); console.log(result);
The replace() method returns a new string with some or all matches of a pattern replaced
by a replacement. 的替换()方法返回与一些或者图案的所有比赛的新字符串
replaced
用替换。 The pattern can be a string or a RegExp
, and the replacement can be a string or a function to be called for each match. 模式可以是字符串或
RegExp
,替换项可以是字符串或每个匹配项要调用的函数。
var str = "Hello! I'm billy! what's up?"; str = str.replace(/ +/g, " "); console.log(str); var strr = "Hello! I'm billy! what's up?"; strr = strr.replace(/ +/g, " "); console.log(strr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.