A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Convert Comma Separated String into an Array in JavaScript
Q:

How to Convert Comma Separated String into an Array in JavaScript

0

How to Convert Comma Separated String into an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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.

The following example demonstrates how to convert a comma separated string of person name into an array and retrieve the individual name using JavaScript.

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now