用 JavaScript 字符串中的单个空格替换多个空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6163169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace multiple whitespaces with single whitespace in JavaScript string
提问by eve
I have strings with extra whitespaces, each time there's more than only one whitespace I'd like it be only one.
我有带有额外空格的字符串,每次有不止一个空格时,我希望它只有一个。
Anyone? I tried searching google, but nothing worked for me.
任何人?我尝试搜索谷歌,但没有任何对我有用。
Thanks
谢谢
回答by bjornd
Something like this:
像这样的东西:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
回答by gui pn
You can augment String to implement these behaviors as methods, as in:
您可以扩充 String 以将这些行为实现为方法,如下所示:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
现在,您可以使用以下优雅的形式来生成所需的字符串:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
回答by Roger Gajraj
using a regular expression with the replace function does the trick:
使用带有替换函数的正则表达式可以解决问题:
string.replace(/\s/g, "")
回答by vsync
Here's a non-regex solution (just for fun):
这是一个非正则表达式解决方案(只是为了好玩):
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 ES6:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
它通过whitespaces分割字符串,从数组中删除所有空数组项(超过一个空格的那些),并将所有单词再次连接成一个字符串,它们之间有一个空格。
回答by Spudley
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing allspaces?
我想您希望从字符串的开头和/或结尾去除空格(而不是删除所有空格?
If that's the case, you'll need a regex like this:
如果是这种情况,您将需要一个这样的正则表达式:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
这将删除字符串开头或结尾的所有空格。如果您只想从末尾修剪空格,则正则表达式将如下所示:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
希望有帮助。
回答by chug2k
回答by Markku Uttula
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
我知道我不应该对某个主题进行通灵术,但鉴于问题的详细信息,我通常会将其扩展为:
- I want to replace multiple occurences of whitespace inside the string with a single space
- ...and... I do not want whitespaces in the beginnin or end of the string (trim)
- 我想用一个空格替换字符串中多次出现的空格
- ...和...我不希望在字符串的开头或结尾有空格(修剪)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
为此,我使用这样的代码(第一个正则表达式上的括号只是为了使代码更具可读性......除非您熟悉它们,否则正则表达式可能会很痛苦):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
这样做的原因是 String-object 上的方法返回一个字符串对象,您可以在该对象上调用另一个方法(就像 jQuery 和其他一些库一样)。如果您想在单个对象上连续执行多个方法,则编码方式要紧凑得多。
回答by Praveen Kumar Thalluri
var x = " Test Test Test ".split(" ").join(""); alert(x);
var x = " Test Test Test ".split(" ").join(""); 警报(x);
回答by Richard Vergis
Try this.
尝试这个。
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
结果将是
string 1
What happened here is that it will trim the outside spaces first using trim()
then trim the inside spaces using .replace(/\s+/g, ' ')
.
这里发生的事情是,它将首先使用trim()
修剪外部空间,然后使用.replace(/\s+/g, ' ')
.
回答by user3413723
How about this one?
这个怎么样?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
产出 "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
这个也摆脱了任何标签