Javascript 正则表达式用一个空格替换多个空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1981349/
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
Regex to replace multiple spaces with a single space
提问by AnApprentice
Given a string like:
给定一个字符串,如:
"The dog has a long tail, and it is RED!"
What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?
什么样的 jQuery 或 JavaScript 魔术可以用来将空格保持在一个空格最大值?
Goal:
目标:
"The dog has a long tail, and it is RED!"
回答by BalusC
Given that you also want to cover tabs, newlines, etc, just replace \s\s+with ' ':
鉴于您还想覆盖制表符、换行符等,只需替换\s\s+为' ':
string = string.replace(/\s\s+/g, ' ');
If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:
如果您真的只想覆盖空格(因此不包含制表符、换行符等),请执行以下操作:
string = string.replace(/ +/g, ' ');
回答by Edward Loper
Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:
由于您似乎对性能感兴趣,因此我使用 firebug 对这些进行了分析。以下是我得到的结果:
str.replace( / +/g, ' ' ) -> 380ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( / +/g, ' ' ) -> 790ms
str.replace( / +(?= )/g, ' ') -> 3250ms
This is on Firefox, running 100k string replacements.
这是在 Firefox 上,运行 100k 字符串替换。
I encourage you to do your own profiling tests with firebug, if you think performance is an issue. Humans are notoriously bad at predicting where the bottlenecks in their programs lie.
如果您认为性能有问题,我鼓励您使用 firebug 进行自己的分析测试。众所周知,人类不擅长预测他们程序中的瓶颈所在。
(Also, note that IE 8's developer toolbar also has a profiler built in -- it might be worth checking what the performance is like in IE.)
(另外,请注意 IE 8 的开发人员工具栏也有一个内置的分析器——可能值得检查一下 IE 中的性能如何。)
回答by watain
var str = "The dog has a long tail, and it is RED!";
str = str.replace(/ {2,}/g,' ');
EDIT:If you wish to replace all kind of whitespace characters the most efficient way would be like that:
编辑:如果你想替换所有类型的空白字符,最有效的方法是这样的:
str = str.replace(/\s{2,}/g,' ');
回答by meder omuraliev
This is one solution, though it will target allspace characters:
这是一种解决方案,但它将针对所有空格字符:
"The dog has a long tail, and it is RED!".replace(/\s\s+/g, ' ')
"The dog has a long tail, and it is RED!"
Edit: This is probably better since it targets a space followed by 1 or more spaces:
编辑:这可能更好,因为它的目标是一个空格,后跟 1 个或多个空格:
"The dog has a long tail, and it is RED!".replace(/ +/g, ' ')
"The dog has a long tail, and it is RED!"
Alternative method:
替代方法:
"The dog has a long tail, and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"
I didn't use /\s+/by itself since that replaces spaces that span 1 character multiple times and might be less efficient since it targets more than necessary.
我没有/\s+/单独使用它,因为它多次替换跨越 1 个字符的空格,并且可能效率较低,因为它的目标超出了必要的范围。
I didn't deeply test any of these so lmk if there are bugs.
我没有深入测试任何这些所以 lmk 如果有错误。
Also, if you're going to do string replacement remember to re-assign the variable/property to its own replacement, eg:
此外,如果您要进行字符串替换,请记住将变量/属性重新分配给它自己的替换,例如:
var string = 'foo'
string = string.replace('foo', '')
Using jQuery.prototype.text:
使用 jQuery.prototype.text:
var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )
回答by Nenotlep
I have this method, I call it the Derp method for lack of a better name.
我有这个方法,我称它为 Derp 方法,因为没有更好的名字。
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
回答by Ethan
A more robust method: This takes care of alsoremoving the initial and trailing spaces, if they exist. Eg:
一个更健壮的方法:这还负责删除初始和尾随空格(如果它们存在)。例如:
// NOTE the possible initial and trailing spaces
var str = " The dog has a long tail, and it is RED! "
str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// str -> "The dog has a long tail, and it is RED !"
Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.
您的示例没有这些空格,但它们也是一个非常常见的场景,并且接受的答案只是将它们修剪为单个空格,例如:“ The ... RED!”,这不是您通常需要的。
回答by Chris
More robust:
更强大:
function trim(word)
{
word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
return word.replace(/^\s+|\s+$/g, ''); // remove leading/trailing spaces
}
回答by Leonard Meagher
I suggest
我建议
string = string.replace(/ +/g," ");
for just spaces
OR
仅用于空格
或
string = string.replace(/(\s)+/g,"");
for turning multiple returns into a single return also.
也用于将多次回报转换为单一回报。
回答by imos
Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)
如果您不想使用替换,这是一个替代解决方案(替换字符串中的空格而不使用替换 javascript)
var str="The dog has a long tail, and it is RED!";
var rule=/\s{1,}/g;
str = str.split(rule).join(" ");
document.write(str);
回答by ToXic73
I know that I am late to the party, but I discovered a nice solution.
我知道我迟到了,但我发现了一个很好的解决方案。
Here it is:
这里是:
var myStr = myStr.replace(/[ ][ ]*/g, ' ');

