Convert String to Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert a given string into an array of words using JavaScript. We will use the String.prototype.split() method to split the string and the Array.prototype.filter() method to remove any empty strings. By the end of the lab, you will have a better understanding of how to manipulate strings in JavaScript and extract meaningful data from them.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28628{{"`Convert String to Array`"}} javascript/data_types -.-> lab-28628{{"`Convert String to Array`"}} javascript/arith_ops -.-> lab-28628{{"`Convert String to Array`"}} javascript/comp_ops -.-> lab-28628{{"`Convert String to Array`"}} javascript/higher_funcs -.-> lab-28628{{"`Convert String to Array`"}} end

Function to Convert String into an Array of Words

To convert a given string into an array of words, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the String.prototype.split() method with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings.
  3. Use the Array.prototype.filter() method to remove any empty strings.
  4. Omit the second argument, pattern, to use the default regexp.

Here's a function that implements these steps:

const words = (str, pattern = /[^a-zA-Z-]+/) =>
  str.split(pattern).filter(Boolean);

You can use the words() function with different strings to convert them into arrays of words:

words("I love javaScript!!"); // ['I', 'love', 'javaScript']
words("python, javaScript & coffee"); // ['python', 'javaScript', 'coffee']

Summary

Congratulations! You have completed the String to Words lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like