Javascript 拆分空格分隔的字符串并修剪额外的逗号和空格 [英] Javascript Split Space Delimited String and Trim Extra Commas and Spaces

查看:27
本文介绍了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.

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

这篇关于Javascript 拆分空格分隔的字符串并修剪额外的逗号和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆