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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11211175/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:55:33  来源:igfitidea点击:

Javascript Split Space Delimited String and Trim Extra Commas and Spaces

javascriptstringsplittrim

提问by User970008

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";

Output to this string:

输出到这个字符串:

ford,tempo,with,sunroof,

I need the trailing comma and no spaces in the final output.

我需要尾随逗号并且最终输出中没有空格。

Not sure if I should go Regex or a string splitting function.

不确定我是否应该使用 Regex 或字符串拆分函数。

Anyone do something like this already?

有人已经做过这样的事情了吗?

I need to use javascript (or JQ).

我需要使用 javascript(或 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);

回答by Felix Kling

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.

如果前面和后面有空格,则应先删除它们。

Reference:.split, .replace, Regular Expressions

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

回答by Richard

In addition to Felix Kling's answer

除了Felix Kling回答

If you have preceding and trailing white spaces, you should remove those first.

如果前面和后面有空格,则应先删除它们。

It's possible to add an "extension method" to a JavaScript Stringby hooking into it's prototype. I've been using the following to trim preceding and trailing white-spaces, and thus far it's worked a treat:

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

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

回答by Chaos

In ES6:

ES6 中

var temp = str.split(",").map((item)=>item.trim());

回答by Benny Bottema

I would keep it simple, and just match anything notallowed instead to join on:

我会保持它的简单,只是匹配任何容许,而不是加入的:

str.split(/[^a-zA-Z-]+/g).filter(v=>v);

This matches all the gaps, no matter what non-allowed characters are in between. To get rid of the empty entry at the beginning and end, a simple filter for non-null values will do. See detailed explanation on regex101.

这匹配所有间隙,无论中间有什么不允许的字符。为了摆脱开头和结尾的空条目,可以使用一个简单的非空值过滤器。请参阅有关 regex101 的详细说明

var str = ", ,, ford,    tempo, with,,, sunroof,, ,";

var result = str.split(/[^a-zA-Z-]+/g).filter(v=>v).join(',');

console.info(result);

回答by Ferenc Takacs

If you just want to split, trimand joinkeeping the whitespaces, you can do this with lodash:

如果您只想拆分、修剪连接保留空格,您可以使用lodash执行此操作

// The string to fix
var stringToFix = "The Wizard of Oz,Casablanca,The Green Mile";

// split, trim and join back without removing all the whitespaces between
var fixedString = _.map(stringToFix.split(','), _.trim).join(' == ');

// output: "The Wizard of Oz == Casablanca == The Green Mile"
console.log(fixedString);
<script src="https://cdn.jsdelivr.net/lodash/4.16.3/lodash.min.js"></script>