[英]Replacing, regex, javascript
Got this string: 得到了这个字符串:
'test',$, #207
I need to remove spaces which have a commma before 我需要删除之前有逗号的空格
So the result will be: 'test',$,#207
因此结果将是: 'test',$,#207
Tried this: 试过这个:
replace(/\/s,]/g, ',')
Not working. 不工作 Any ideas? 有任何想法吗?
由于您的模式很简单,因此只需执行.split(', ').join(',')
To replace only spaces and not other whitespaces
use the following regex. 要仅替换空格而不替换其他whitespaces
使用以下正则表达式。
Regex : /, +/g
正则表达式 : /, +/g
Explanation : 说明 :
,
will search for comma. ,
将搜索逗号。
+
will search for multiple spaces. +
将搜索多个空格。
And then replace by ,
using replace(/, +/g, ',')
然后替换通过,
使用replace(/, +/g, ',')
replace(new RegExp(find, ', '), ',');
I need to remove spaces which have a commma afterwards 我需要删除带有逗号的空格
No, your example says the opposite. 不,您的示例相反。 That is, you want to remove spaces that have a comma before them. 也就是说,您要删除在其前面有逗号的空格。
In either case, the error in your expression is the "]". 无论哪种情况,表达式中的错误都是“]”。
replace(/\/s,/g, ',')
Does what you say you want to do, and 你说你想做什么,并且
replace(/,\/s/g, ',')
Does what the example says. 如示例所示。
The other answer is right, though - just use replace(' ,', '')
; 另一个答案是正确的-只需使用replace(' ,', '')
; you need no regex here. 您无需在这里使用正则表达式。
I think you meant comma that have whitespace afterwards: 我认为您的意思是逗号后面要有空格:
stringVar = "'test',$, #207";
replace('/\,\s/g', stringVar);
\\,
means ,
literally and \\s
means whitespace. \\,
装置,
字面上和\\s
是指空白。
You can test javascript regex and know a little more about the modifiers and stuff at regex101 . 您可以测试javascript regex,并在regex101上了解有关修饰符和内容的更多信息。
For all whitespaces which have a "," before 对于前面带有“,”的所有空格
var str = "test,$, #207, th, rtt878";
console.log(str.replace(/\,\s+/g,","));
var str = "test,$, #207";
console.log(str.replace(/\,\s+/g,","));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.