Javascript 拆分空格分隔的字符串并修剪额外的逗号和空格
我需要拆分关键字字符串并将其转换为逗号分隔的字符串.但是,我需要删除用户已经输入的多余空格和任何逗号.
I need to split a keyword string and turn it into a comma delimited string. However, I need to get rid of extra spaces and any commas that the user has already input.
var keywordString = "ford tempo, with,,, sunroof";
输出到这个字符串:
ford,tempo,with,sunroof,
我需要结尾的逗号并且在最终输出中没有空格.
I need the trailing comma and no spaces in the final output.
不确定我是否应该使用 Regex 或字符串拆分函数.
Not sure if I should go Regex or a string splitting function.
有人做过这样的事情吗?
Anyone do something like this already?
我需要使用 javascript(或 JQ).
I need to use javascript (or JQ).
编辑(工作解决方案):
EDIT (working solution):
var keywordString = ", ,, ford, tempo, with,,, sunroof,, ,";
//remove all commas; remove preceeding and trailing spaces; replace spaces with comma
str1 = keywordString.replace(/,/g , '').replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/[\s,]+/g, ',');
//add a comma at the end
str1 = str1 + ',';
console.log(str1);
在这两种情况下,您都需要正则表达式.您可以拆分并加入字符串:
You will need a regular expression in both cases. You could split and join the string:
str = str.split(/[\s,]+/).join();
这会拆分并消耗任何连续的空格和逗号.同样,您可以匹配和替换这些字符:
This splits on and consumes any consecutive white spaces and commas. Similarly, you could just match and replace these characters:
str = str.replace(/[\s,]+/g, ',');
对于尾随逗号,只需附加一个
For the trailing comma, just append one
str = .... + ',';
如果前后有空格,则应先删除它们.
If you have preceding and trailing white spaces, you should remove those first.