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.
Anyone do something like this already?
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);
In ES6:
If you just want to split, trim and join keeping the whitespaces, you can do this with lodash:
I would keep it simple, and just match anything not allowed instead to join on:
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.
In addition to Felix Kling's answer
It's possible to add an "extension method" to a JavaScript
String
by 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:You will need a regular expression in both cases. You could split and join the string:
This splits on and consumes any consecutive white spaces and commas. Similarly, you could just match and replace these characters:
For the trailing comma, just append one
If you have preceding and trailing white spaces, you should remove those first.
Reference:
.split
,.replace
, Regular Expressions