. Advertisement .
..3..
. Advertisement .
..4..
JavaScript is a programming language or scripting that enables you to execute complex attributes on web pages. Numerous websites utilize the lightweight, object-oriented programming language JavaScript (js) to script their webpages. If you don’t know how to convert a comma separated string into an array in Javascript, please refer to some of the solutions we give below.
To convert a comma separated string to array in JavaScript
What can we do to convert a comma separated string into an array in Javascript? Let’s read two following methods, they will help you.
Use the split() method
The first way that you can try to convert a comma separated string into an array in JavaScript is to use the split()
method. This solution relies on an extractor to partition a sequence. And to distinguish strings in the case, a comma is present; delimiters will be described as commas
Syntax: string.split(separator, limit)
Sample code
orgStr = "Mo, Tu, We, Th, Fr, Sa, Su";
newArr = originalString.split(', ');
Result:
String: "Mo, Tu, We, Th, Fr, Sa, Su"
Array: Mo, Tu, We, Th, Fr, Sa, Su
Now with this solution, you can convert a comma separated string into an array in JavaScript.
Use the slice() method
This solution will iterate over every single character in the string and check for commas. A previous index variable will track the first character of the following string. Then, the slice()
method is applied to eliminate the part of the previous index string and the existing position of the comma. Then the middle string above will be pushed to a new array. The process will repeat for the total length of the string. And the array containing all the strings that be split is the final array.
Syntax: string.slice(start,end)
Code example
orgStr = "Mo, Tu, We, Th, Fr, Sa, Su";
newArr = [];
// index of end of the last string
let preIndex = 0;
for (i = 0; i < orgStr.length; i++) {
if (orgStr[i] == ', ') {
// split the string by the comma
separated = orgStr.slice(preIndex, i);
newArr.push(separated);
preIndex = i + 1;
}
}
// push the last string into the array
newArr.push(orgStr.slice(preIndex, i));
Result:
String: "Mo, Tu, We, Th, Fr, Sa, Su"
Array: Mo, Tu, We, Th, Fr, Sa, Su
Conclusion
Thus, you can refer to two methods mentioned above to convert a comma separated string to array in JavaScript. We hope this article is helpful to you. If you have any questions or problems with IT, let’s contact us by leaving comment below. We are always willing to help you. Thank you for your reading!
Read more:
Leave a comment