Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

I have checked many questions and answers regarding join array with comma separated string, But my problem is that, I am making the string readable for human i.e I have tags array that's if their is two tags, then it would be tag1 and tag2 and if their is 100 tags then it would be tag1, tag2, ,,,tag99 and tag100 for last one use the and and before using the comma as a separator.

Any way to handle in JQuery?

like image 289
Suleman Ahmad Avatar asked Apr 27 '13 11:04

Suleman Ahmad


People also ask

How do you create an array with comma-separated strings?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you get comma-separated values in an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do I convert an array to a string without commas?

To convert an array to a string without commas, call the join() method on the array, passing it an empty string as a parameter - arr. join('') . The join method returns a string containing all array elements joined by the provided separator. Copied!

How do you get a comma-separated string from an array in C?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.


1 Answers

You can use .slice():

> var a = [1, 2, 3, 4, 5]; > [a.slice(0, -1).join(', '), a.slice(-1)[0]].join(a.length < 2 ? '' : ' and '); '1, 2, 3, 4 and 5' 
  • a.slice(0, -1).join(', '): takes all but the last element and joins them together with a comma.
  • a.slice(-1)[0]: it's the last element.
  • .join(a.length < 2 ? '' : ' and '): joins that string and the last element with and if there are at least two elements.
like image 133
Blender Avatar answered Sep 29 '22 09:09

Blender