Javascript - 如何删除单词之间的所有额外间距 [英] Javascript - How to remove all extra spacing between words
问题描述
如何删除字符串文字中单词之间的所有额外空格?
How can I remove all extra space between words in a string literal?
"some value"
应该成为
"some value"
此外,
" This should become something else too . "
成为
"This should become something else too ."
不要担心移动。
。就像上面的情况一样好。我知道我可以使用 $ .trim(str)
来实现尾随/结束空间的移除。但是,我不确定如何在单词技巧之间做1个空格。
Do not worry about moving the .
. Just as above is fine. I know I can use $.trim(str)
to achieve the trailing/ending space removal. But, I'm not sure how to do the 1 space between words trick.
推荐答案
var string = " This should become something else too . ";
string = string.replace(/\s+/g, " ");
此代码替换一组连续的空白字符( \s +
)由一个空格组成。请注意,空格字符还包括制表符和换行符。如果您只想替换空格,请用空格替换 \s
。
This code replaces a consecutive set of whitespace characters (\s+
) by a single white space. Note that a white-space character also includes tab and newlines. Replace \s
by a space if you only want to replace spaces.
如果您还想删除开头和结尾的空格包括:
If you also want to remove the whitespace at the beginning and end, include:
string = string.replace(/^\s+|\s+$/g, "");
此行删除开头的所有空白字符( ^
)和结束( $
)。 RegExp末尾的 g
表示:全局,即匹配并替换所有出现的事件。
This line removes all white-space characters at the beginning (^
) and end ($
). The g
at the end of the RegExp means: global, ie match and replace all occurences.
这篇关于Javascript - 如何删除单词之间的所有额外间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!