In this blog post, you'll learn how to create an array of words from a given string using JavaScript. Turn any string into an array of words: This Guide will teach you how you can split words from a string and make an array of words.
It's simple to convert the given string into an array using JavaScript. You can achieve this using the split() method. Here's how:
Using split method.
JavaScript
// With space.
let string = " Hello welcome to maketechstuff.com ";
let array = string.split(" ");
console.log("string: ", string);
console.log("array: ", array);
Output:
The above approach also includes spaces within the array. If you want to exclude the spaces and obtain only the array of words or obtain only the non empty elements inside an array, you can do like this ways:
Way 1: Using split and filter method.
Convert the string into an array of words using the split method.
Create a new array by filtering the existing array using the filter method. The filter method will exclude empty elements, resulting in an array containing only non-empty words.
JavaScript
// Way 1:
// Without space.
let string = " Hello welcome to maketechstuff.com ";
let array = string.split(" ");
let new_array = array.filter(function (array) { return array });
console.log("String: ", string);
console.log("array: ", array);
console.log("new_array: ",new_array);
Output:
Way 2: Using split and push method with for loop.
Use the split method to split a string into an array of strings based on a delimiter.
Create a new empty array to store the non-empty elements.
Iterate through the original array (array of a string, which we convert using split method) using a for loop. For each element, check if it's not empty. If it's not empty, add it to the new array (which we created , an empty array) using the push method.
Resulting, array will contain only the non-empty elements from the original array.
JavaScript
// Way 2:
// Without space.
let string = " Hello welcome to maketechstuff.com ";
let array = string.split(" ");
let new_array = [];
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (element !== "") {
new_array.push(element);
}
}
console.log("string: ", string);
console.log("array: ", array);
console.log(": new_array", new_array);
Output:
So that's how you can convert the string into an array of words using JavaScript. If you have any questions or suggestions you can write in the comment section.
You may like:
- How to convert the given string into an array of characters using JavaScript.
- How to count the characters present inside an string using JavaScript.
- How to count the words present inside a given string using JavaScript.
- How to create a word counter using JavaScript.
Share your thoughts.