Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  9] [ 2]  / answers: 1 / hits: 44109  / 12 Years ago, tue, june 26, 2012, 12:00:00

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(/^ss*/, '').replace(/ss*$/, '').replace(/[s,]+/g, ',');


//add a comma at the end
str1 = str1 + ',';

console.log(str1);

More From » string

 Answers
40

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


[#84652] Monday, June 25, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
;