Javascript 正则表达式在Javascript中的每个逗号后添加一个空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7621066/
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 add a space after each comma in Javascript
提问by Plasticated
I have a string that is made up of a list of numbers, seperated by commas. How would I add a space after each comma using Regex?
我有一个由数字列表组成的字符串,用逗号分隔。如何使用正则表达式在每个逗号后添加一个空格?
回答by kzh
Simplest Solution
最简单的解决方案
"1,2,3,4".replace(/,/g, ', ')
//-> '1, 2, 3, 4'
Another Solution
另一个解决方案
"1,2,3,4".split(',').join(', ')
//-> '1, 2, 3, 4'
回答by eliocs
I find important to note that if the comma is already followed by a space you don't want to add the space:
我发现重要的是要注意,如果逗号后面已经跟一个空格,您不想添加空格:
"1,2, 3,4,5".replace(/,(?=[^\s])/g, ", ");
> "1, 2, 3, 4, 5"
This regex checks the following character and only replaces if its no a space character.
此正则表达式检查以下字符,并且仅在没有空格字符时才替换。
回答by user3375803
Another simple generic solution for comma followed by n spaces:
逗号后跟 n 个空格的另一个简单通用解决方案:
"1,2, 3, 4,5".replace(/,[s]*/g, ", ");
> "1, 2, 3, 4, 5"
Always replace comma and n spaces by comma and one space.
始终用逗号和一个空格替换逗号和 n 个空格。
回答by Matt Ball
Use String.replace
with a regexp.
> var input = '1,2,3,4,5',
output = input.replace(/(\d+,)/g, ' ');
> output
"1, 2, 3, 4, 5"
回答by Daniel R Guzman
Those are all good ways butin cases where the input is made by the user and you get a list like "1,2, 3,4, 5,6,7"
这些都是好方法,但在用户输入的情况下,你会得到一个像“1,2,3,4,5,6,7”这样的列表
..In which case lets make it idiot proof! So accounting for the already formatted parts of the string, the solution:
..在这种情况下,让它证明白痴!因此,考虑到字符串已经格式化的部分,解决方案:
"1,2, 3,4, 5,6,7".replace(/, /g, ",").replace(/,/g, ", ");
//result: "1, 2, 3, 4, 5, 6, 7" //Bingo!
回答by epascarello
var numsStr = "1,2,3,4,5,6";
var regExpWay = numStr.replace(/,/g,", ");
var splitWay = numStr.split(",").join(", ");
回答by Martin Jespersen
Don't use a regex for this, use split and join.
不要为此使用正则表达式,请使用拆分和连接。
It's simpler and faster :)
它更简单,更快:)
'1,2,3,4,5,6'.split(',').join(', '); // '1, 2, 3, 4, 5, 6'
回答by Benoit Thiery
As I came here and did not find a good generic solution, here is how I did it:
当我来到这里并没有找到一个好的通用解决方案时,我是这样做的:
"1,2, 3,4,5".replace(/,([^\s])/g, ", ");
This replaces comma followed by anything but a space, line feed, tab... by a comma followed by a space.
这将替换逗号后跟除空格、换行符、制表符以外的任何内容...由逗号后跟空格替换。
So the regular expression is:
所以正则表达式是:
,([^\s])
and replaced by
并替换为
,