JavaScript: Convert a given string into an array of words
JavaScript fundamental (ES6 Syntax): Exercise-103 with Solution
Write a JavaScript program to convert a given string into an array of words.
- Use String.prototype.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings.
- Use Array.prototype.filter() to remove any empty strings.
- Omit the second argument, pattern, to use the default regexp.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
console.log(words('I love javaScript!!'));
console.log(words('python, java, php'));
Sample Output:
["I","love","javaScript"] ["python","java","php"]
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-103-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to create an array of elements, grouped based on the position in the original arrays.
Next: Write a JavaScript program to test a value, x, against a predicate function. If true, return fn(x). Else, return x.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- 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