String with commas to array javascript

How to convert a comma-separated string to an array in JavaScript

In this post, we will learn different ways to convert a comma separated string to an array. For example, we can convert the string one,two,three,four,five to the array [‘one’, ‘two’, ‘three’, ‘four’, ‘five’]. This is a common problem we faced in frontend or backend development. JavaScript provides a couple of functions those can be used to do it easily.

Let me show you these functions with examples:

We can pass ’,’ to the split function as its parameter and it will return the words in the string in an array. If you don’t provide any parameter to split, it breaks the string at blank spaces.

let givenString = 'one,two,three,four,five'; let arr = givenString.split(','); console.log(arr);

It will split the string and put the words in the array arr. If you run this program, it will print the below output:

Читайте также:  Create scanner class java

If there is an empty string, i.e. two , without a word in between, it will put one empty string to the array. For example,

let givenString = 'one,two. three'; let arr = givenString.split(','); console.log(arr);

It will put three empty strings to the array.

If you want to remove these empty strings, you can array a filter operation to the result array to remove all strings with 0 length.

let givenString = 'one,two. three'; let arr = givenString.split(',').filter(e => e && e.length > 0); console.log(arr);
let givenString = 'one,two. three'; let arr = givenString.split(',').filter(e => e); console.log(arr);

split and leading/trailing spaces:

We can also have strings with leading and trailing spaces and you might want to remove these spaces before doing any other processing. For example,

let givenString = 'one ,two . three'; let arr = givenString.split(',').filter(e => e); console.log(arr);

So, if we want to remove the leading and trailing spaces from these words, we can iterate through the array items using map and remove the spaces using trim():

let givenString = 'one ,two . three'; let arr = givenString.split(',').filter(e => e).map(e => e.trim()); console.log(arr);

split and regular expression/regex:

We can pass a regular expression or regex to split. For example, in the below example program,

let givenString = 'one ,two . three'; let arr = givenString.split(/\s*,+\s*/); console.log(arr);

This regular expression will remove all leading and trailing spaces from the words and also it will also remove the empty strings. Basically, this regular expression will remove the use of filter and map.

So, if you run this code, it will give the below result:

javascript comma separated string to array

Источник

String with commas to array javascript

Last updated: Jan 2, 2023
Reading time · 5 min

banner

# Table of Contents

# Convert a comma-separated String to an Array in JavaScript

Use the String.split() method to convert a comma-separated string to an array.

The split() method will split the string on each occurrence of a comma and will return an array containing the results.

Copied!
// 👇️ to array of strings const str = 'bobby,hadz,com'; const arr = str.split(','); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(arr); console.log(arr[0]); // 👉️ bobby console.log(arr[1]); // 👉️ hadz // ----------------------------------------- // 👇️ to array of numbers const str2 = '1,2,3,4,5,6'; const arr2 = str2.split(',').map(Number); console.log(arr2); // 👉️ [ 1, 2, 3, 4, 5, 6 ]

We used the String.split() method to split a string into an array.

The only argument we passed to the method is a separator. The separator marks where each split should occur.

If the words in your string are separated by a comma followed by a space, pass a comma and a space as the separator to the split() method.

Copied!
const str = 'bobby, hadz, com'; const arr = str.split(', '); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(arr);

If the split() method is called on an empty string, it returns an array containing an empty string.

Copied!
const str = ''; const arr = str.split(','); console.log(arr); // 👉️ ['']

If you want to get an empty array when the string is empty, use the Array.filter() method.

Copied!
const str = ''; const arr = str.split(',').filter(element => element !== ''); console.log(arr); // 👉️ []

The filter method returns a new array containing only the elements that meet the condition.

# Handling a comma followed by a variable number of spaces

If your string might contain a comma followed by one or more spaces, pass a regular expression to the String.split() method.

Copied!
const str = 'bobby,hadz,com'; function commaSeparatedToArray(str) return str.split(/[ ,]+/); > // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby,hadz,com')); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby,,hadz,,com')); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby, hadz, com')); // 👇️ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby, hadz, com'));

The forward slashes / / mark the beginning and end of the regular expression.

The brackets [] are called a character class and match the specified characters.

In our case, spaces and commas.

The plus + matches the preceding item (spaces and commas) one or more times.

In its entirety, the regular expression splits the string by one or more consecutive spaces and commas.

If you need to get an array of numbers, use the map() method.

Copied!
const str = 'bobby,hadz,com'; function commaSeparatedToArray(str) return str.split(/[ ,]+/).map(Number); > // 👇️ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1,2,3')); // 👇️ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1,,2,,3')); // 👇️ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1, 2, 3')); // 👇️ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1, 2, 3'));

The function we passed to the Array.map() method gets called with each element in the array.

On each iteration, we use the Number constructor to convert the current value to a number and return the result.

The map() method returns a new array containing the values returned from the callback function.

# Convert a comma-separated string to an Array of Numbers

To convert a comma-separated string to a numeric array:

  1. Use the split() method to split the string into an array of digits.
  2. Use the map() method to iterate over the array.
  3. Convert each string to a number and return the result.
Copied!
const str = '12,34,56,78,9'; const arr = str.split(',').map(element => return Number(element); >); // 👇️ [12, 34, 56, 78, 9] console.log(arr);

If your string might contain non-numeric values or empty values between commas, scroll down to the next solution.

We used the String.split() method to split the string on each comma.

The split() method divides a string into an array of substrings based on a separator.

By splitting the string on each comma, we get an array containing the digits.

Copied!
const str = '12,34,56,78,9'; // 👇️️ ['12', '34', '56', '78', '9'] console.log(str.split(','));

The last step is to convert each string in the array to a number.

The function we passed to the Array.map() method gets called with each element in the array.

On each iteration, we use the Number() constructor to convert the string to a number and return the result.

The map() method returns a new array containing the values returned from the callback function.

However, if your string contains empty values between commas, non-numeric characters or punctuation, you have to filter the results first.

Copied!
const str = '12,34,,a. 56. 78,9'; const arr = str .split(',') .filter(element => if (element.trim() === '') return false; > return !isNaN(element); >) .map(element => return Number(element); >); // 👇️ [12, 34, 56, 78, 9] console.log(arr);

In this example, our string contains empty values between the commas, some letters and punctuation.

The function we passed to the Array.filter method gets called with each element in the array.

The filter() method returns a new array that only contains the elements that meet the condition.

We first check if the element is equal to an empty string or contains only whitespace and return false if it does.

Finally, we use the isNaN function to check if the provided string is not a number.

We used the logical NOT (!) operator to negate the value returned from the isNaN() function.

The isNaN (is not a number) method tries to convert the string to a number and returns true if it fails.

Copied!
console.log(isNaN('hello')); // 👉️ true console.log(isNaN('')); // 👉️ false console.log(isNaN(' ')); // 👉️ false

This seems quite confusing at first, but the isNaN function converts an empty string or a string containing spaces to a number and gets a value of 0 , so it returns false .

Copied!
console.log(Number('')); // 👉️ 0 console.log(Number(' ')); // 👉️ 0

This is why we used the trim() method to trim the string and verify that it’s not an empty string.

We know that if the isNaN function gets called with a string that contains at least 1 character and returns true , the string is NOT a valid number.

Conversely, if the isNaN function gets called with a string that contains at least 1 character and returns false , then the string is a valid number.

Here are some more examples of calling isNaN with strings.

Copied!
console.log(isNaN('123')); // 👉️ false console.log(isNaN('1.23')); // 👉️ false console.log(isNaN('1,23')); // 👉️ true console.log(isNaN('123test')); // 👉️ true

Only numeric values are contained in the array that the filter() method returns.

This enables us to call the map() method on the array to convert each string to a number.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Convert a Comma-Separated String to an Array in JavaScript?

Depending on whether your comma-separated string has whitespaces, you can do the following to convert it into an array:

Convert Comma-Separated String With No Spaces Into an Array

You can convert a JavaScript comma-separated string (which has no spaces) into an array by using the String.prototype.split() method, for example, like so:

const str = 'foo,bar,baz,qux'; console.log(str.split(',')); // ['foo', 'bar', 'baz', 'qux']

Convert Comma-Separated String With Set Sequence of Repeating Spaces Into an Array

If the comma-separated string has a known number of spaces in a repeating sequence (e.g. » , «), then you can simply specify it as the delimiter to the String.prototype.split() method, for example, like so:

const str = 'foo, bar, baz, qux'; console.log(str.split(', ')); // ['foo', 'bar', 'baz', 'qux']

Convert Comma-Separated String With Unknown Whitespaces Into an Array

If your string has unknown number of whitespaces before/after in any order/number, then you can use Array.prototype.map() to iterate over each item in the resulting array (from String.prototype.split() ) and use String.prototype.trim() to trim any whitespaces:

const str = ' foo , bar,baz, qux '; const arr = str.split(',').map((item) => item.trim()); console.log(arr); // ['foo', 'bar', 'baz', 'qux']

This also works as expected when there’s a set sequence of repeating spaces in the string. For example:

const str = 'foo, bar, baz, qux'; const arr = str.split(',').map((item) => item.trim()); console.log(arr); // ['foo', 'bar', 'baz', 'qux']

Hope you found this post useful. It was published 16 Sep, 2022 . Please show your love and support by sharing this post.

Источник

String with commas to array javascript

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью