user13542454
user13542454

Reputation:

How to split string and create an array?

let name = "Stack Overflow"

I want to ignore space and create an array with each alphabet as an element.

Expected result: ["S", "t", "a", "c", "k", "O", "v", "e", "r", "f", "l", "o", "w"]

Upvotes: 3

Views: 142

Answers (3)

Lucas Andrade
Lucas Andrade

Reputation: 4580

On javascript you're looking for spread (link to docs) operator associate with a filter method (link to docs):

The spread will create an array with all chars from your string, the filter will ignore all spaces for you:

let name = "Stack Overflow"

let myArray = [...name].filter(letter => letter !== ' ');

// myArray will be:
[
  'S', 't', 'a', 'c',
  'k', 'O', 'v', 'e',
  'r', 'f', 'l', 'o',
  'w'
]

This also right for es6 ! Cheer

Upvotes: 0

Sid
Sid

Reputation: 4997

name.replace(/ /g,'')

And then

Array.from(name)

Upvotes: -1

Soham
Soham

Reputation: 725

console.log("Stack Overflow".replace(/\s/g, '').split(''));

Upvotes: 4

Related Questions