convert comma separated string to array javascript code example

Example 1: javascript split by comma

<script>
var names = 'Harry,John,Clark,Peter,Rohn,Alice';
var nameArr = names.split(',');
console.log(nameArr);
 
// Accessing individual values
alert(nameArr[0]); // Outputs: Harry
alert(nameArr[1]); // Outputs: John
alert(nameArr[nameArr.length - 1]); // Outputs: Alice
 
var str = 'Hello World!';
var chars = str.split('');
console.log();
 
// Accessing individual values
alert(chars[0]); // Outputs: H
alert(chars[1]); // Outputs: e
alert(chars[chars.length - 1]); // Outputs: !
</script>

Example 2: javascript array to comma separated string

var colors = ["red", "blue", "green"];
var colorsCSV = colors.join(","); //"red,blue,green"

Example 3: separatly fetch a strings with commas inn js

$(function(){
    var s = "jpeg, jpg, gif, png";
    var match = s.split(', ')
    console.log(match)
    for (var a in match)
    {
        var variable = match[a]
        console.log(variable)
    }
})

Example 4: javascript split string into array by comma and space

input.split(/[ ,]+/); //splits string using RegEx on a space OR a comma

Example 5: convert comma separated string to array c#

string fruit = "Apple,Banana,Orange,Strawberry";
string[] split = fruit.Split(',');

Tags:

R Example