Javascript lines to array

6 Ways to Convert a String to an Array in JavaScript

Arrays are the most powerful data structure in JavaScript. I found myself solving many algorithms by converting strings to arrays. So I thought of consolidating and comparing various ways to do the same. Converting from string to array is always done using the split() method but after ES6, there are many tools we could do the same. Let’s go through each method one by one and discuss the pros and cons of each.

1. Using .split(‘’):

split() is a string method that splits a string into an array of the ordered list with a pattern. This is an ES6 method and is the cleanest way to get the job done.

////* Seperate string by space character(' ') *//// const myFavShow = 'The Office'; const myFavShowArray = myFavShow.split(''); console.log(myFavShowArray) //['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e'] 

Another advantage of this way is we can separate strings by characters or whitespace. Below is an example of how we can do it.

////* Seperate string by whitespace(' ') *//// const myFavShow = 'The Office'; const myFavShowArray = myFavShow.split(' '); console.log(myFavShowArray) //['The', 'Office'] ////* Seperate string by a character '-' *//// const favDialogue = 'Thats-what-she-said'; const favDialogueArr = favDialogue.split('-'); console.log(favDialogueArr) //['Thats', 'what', 'she', 'said'] 

It also works well with Regex too. You can find the complete documentation of split() here. This way flawlessly separates the string elements into an array but it has its limitations.

NOTE: This method does not work very well with uncommon Unicode characters. This method returns the Unicode of the characters instead of actual characters which might make our job a bit more complicated(refer here) but the MDN document has been updated so that we can make it work with Unicode if we just include u flag. See here for more information.

"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ] 

2. Using spread syntax ([…str])

const myFavShow = 'The Office' const myFavShowArray = [. myFavShow] console.log(myFavShowArray) // ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e'] 

It also helps that the limitation we have in the split() has been eliminated here. Consider the below example. We can split any characters easily using this method.

const animal = '🦊🦊' const animalArr = [. animal] console.log(animalArr) // ['🦊', '🦊'] 

3. Using Array.from(str):

The Array. from() method creates a new, shallow-copied Array instance from an iterable or array-like object.

const myFavShow = 'The Office' const myFavShowArray = Array.from(myFavShow); console.log(myFavShowArray) // ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e'] 
const str = '😎😎' const arr = Array.from(str) console.log(arr) // ['😎', '😎'] 

4. Using Object.assign([], str)

The Object. assign() method copies all the properties from one or more source objects to a target object. There are two things to keep in mind about this method though. One is that Object. assign() copies property values called deep copy (Refer here to know the difference between deep copy and shallow copy). One has to keep this in mind before using this method before using it.

const myFavShow = 'The Office' const myFavShowArray = Object.assign([], myFavShow); console.log(myFavShowArray) // ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e'] 

Another is that we have the same trouble as the split() method: it cannot separate uncommon characters (we see Unicode instead of actual characters).

const s = '😄😄' const a = Object.assign([], s); console.log(a) // ['\uD83D', '\uDE04', '\uD83D', '\uDE04'] 

5. Using old school method ( for loop and array.push() )

Although we have a lot of options to play around with, I had to mention this old-school method where we push the elements of the string using the for loopand array method push(). This is not the cleanest way of doing it but it is most definitely worth mentioning who want to stay away from the changing complexities of JavaScript (Although I would prefer other ways).

const s = 'the office'; const a = []; for (const s2 of s)  a.push(s2); > console.log(a); // ['t', 'h', 'e', ' ', 'o', 'f', 'f', 'i', 'c', 'e'] 
const s = '𝟘𝟙𝟚𝟛😄😄'; const a = []; for (const s2 of s)  a.push(s2); > console.log(a); //['𝟘', '𝟙', '𝟚', '𝟛', '😄', '😄'] 

6. Using Array.prototype.slice.call(‘string’)

const favShow = Array.prototype.slice.call("The Office!"); console.log(favShow); //['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e', '!'] 
const favShow = Array.prototype.slice.call("😄😄"); console.log(favShow); //['\uD83D', '\uDE04', '\uD83D', '\uDE04'] 

References:

Conclusion:

To sum it all up, below are the ways we can do the job.

Consolidated ways

That’s 6 ways to convert string to array in JavaScript. Comment below if you used any other methods to get the job done.

Источник

JavaScript: Split a multiline string into an array of lines

JavaScript fundamental (ES6 Syntax): Exercise-139 with Solution

Write a JavaScript program to split a multiline string into an array of lines.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 const splitLines = str => str.split(/\r?\n/); console.log('Original string:'); console.log('This\nis a\nmultiline\nstring.\n'); console.log(splitLines('This\nis a\nmultiline\nstring.\n')); 
Original string: This is a multiline string. ["This","is a","multiline","string.",""]

Pictorial Presentation:

flowchart: Split a multiline string into an array of lines

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

callback function

for (var i = 0; i < 3; i++) < setTimeout(() =>console.log(i), 1); > for (let i = 0; i < 3; i++) < setTimeout(() =>console.log(i), 1); >

Because of the event queue in JavaScript, the setTimeout callback function is called after the loop has been executed. Since the variable i in the first loop was declared using the var keyword, this value was global. During the loop, we incremented the value of i by 1 each time, using the unary operator ++. By the time the setTimeout callback function was invoked, i was equal to 3 in the first example.

In the second loop, the variable i was declared using the let keyword: variables declared with the let (and const) keyword are block-scoped (a block is anything between < >). During each iteration, i will have a new value, and each value is scoped inside the loop.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Java regexp именованные группы
Оцените статью