Javascript分割空格分隔字符串并修剪额外的逗号和空格

Use*_*008 13 javascript string split trim

我需要拆分关键字字符串并将其转换为逗号分隔的字符串.但是,我需要摆脱额外的空格和用户已经输入的任何逗号.

var keywordString = "ford    tempo, with,,, sunroof";
Run Code Online (Sandbox Code Playgroud)

输出到此字符串:

ford,tempo,with,sunroof,
Run Code Online (Sandbox Code Playgroud)

我需要尾随逗号,最终输出中没有空格.

不确定我是否应该使用Regex或字符串拆分功能.

有人做过这样的事吗?

我需要使用javascript(或JQ).

编辑(工作解决方案):

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);
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 33

在这两种情况下,您都需要一个正则表达式.您可以拆分并加入字符串:

str = str.split(/[\s,]+/).join();
Run Code Online (Sandbox Code Playgroud)

这会分裂并消耗任何连续的空格和逗号.同样,您可以匹配并替换这些字符:

str = str.replace(/[\s,]+/g, ',');
Run Code Online (Sandbox Code Playgroud)

对于尾随逗号,只需附加一个

str = .... + ',';
Run Code Online (Sandbox Code Playgroud)

如果您有前面和后面的空格,则应首先删除它们.

参考: .split,.replace,正则表达式


Ric*_*ard 6

除了Felix Kling回答

如果您有前面和后面的空格,则应首先删除它们.

可以String通过挂钩它的原型为JavaScript添加"扩展方法" .我一直在使用以下内容来修剪前面和后面的空格,到目前为止,这是一种享受:

// trims the leading and proceeding white-space
String.prototype.trim = function()
{
    return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
Run Code Online (Sandbox Code Playgroud)


小智 6

ES6中

var temp = str.split(",").map((item)=>item.trim());
Run Code Online (Sandbox Code Playgroud)