Physical Address
Sagipora Sopore Baramulla 193201 Jammu & Kashmir
Hello and welcome to Codipher. Today in this article we will learn how to convert array to string in JavaScript. We will understand 4 easy methods to convert array to string in JavaScript. Also, we will use the real-world usage of these methods. So without wasting further time. Let’s get started with the first method.
Using the toString() method on any array (i.e Array.toString() ) will return the string representation of the array elements.
Array.toString()
This method does not accept any parameter. This method returns a string with all the array values and these are separated by commas.
Also Read: JavaScript Higher Order Functions Explained
The array.join() method combines all the elements of an array into a string and returns that string. The elements of the resultant string will be separated by a specified separator.
Array.join(separator)
This method accepts a single parameter. That parameter is a ‘separator’. The default value of this separator is comma.
The separator is a string that separates each pair of adjacent elements of the array in the resultant string.
This method returns a string with all the array values, separated by the specified separator.
Also Read: Latest JavaScript Features Every Web Developer Should Know
let fruits = ['apple', 'mango', 'banana', 'orange']
console.log(fruits.join(" ")) //output- apple mango banana orange
console.log(fruits.join(";")) //output- apple;mango;banana;orange
console.log(fruits.join()) //output- apple,mango,banana,orange
This method will not change the original array.
We can take advantage of the type coercion in JavaScript. We know that the + operator adds two numbers or concatenates two strings. But what happens, if we join an array with something other than the + operator.
Since JavaScript is a loosely typed language so it isn’t going to crash our program. Instead, it does know how to concatenate strings, it will convert everything into a string.
let fruits = ['apple', 'mango', 'banana', 'orange']
console.log(fruits + "") //output- apple,mango,banana,orange
console.log(fruits + []) //output- apple,mango,banana,orange
What if we have a nested array. Such that array of arrays. The past 3 methods won’t work as expected on nested arrays, here you will need to use JSON.stringify() method.
The JSON.stringify() method converts a JavaScript object or any value to a string.
Also Read: Speed Up Your Website With These Simple CSS Tips
let fruits = ['apple', 'mango', 'banana', 'orange']
let nestedFruits = ['apple', ['mango'], 'banana', 'orange']
console.log(JSON.stringify(fruits)) //output- ["apple, "mango", "banana", "orange"]
console.log(JSON.stringify(nestedFruits)) //output- ["apple, ["mango"], "banana", "orange"]
There are 3 ways through which we can empty an array in javascript. Let’s see these 3 ways.
When setting array.length to 0, all the elements of the array will get removed.
let arr = [1, 2, 3, 4, 5]
arr.length = 0
console.log(arr) //output- []
NOTE- This method mutates the original reference. It means if you will assign one array reference to another with assignment operator (=). Applying this method on one array will clean the other one two.
This is the fastest way. This will set arr to a new empty array. This is perfect if you don’t have any references from other places to the original arr.
If you do, those references won’t be updated and those places will continue to use the old array.
let arr = [1, 2, 3, 4, 5]
arr = []
console.log(arr) //output- []
You can use the splice() method to remove all the elements from an array.
let arr = [1, 2, 3, 4, 5]
arr.splice(0, arr.length)
console.log(arr) //output- []
In the splice() method the first argument is the index of an array to start removing an item from.
The second argument is the number of elements that you want to remove from the index element.
The toString method returns a string representing the source code of the function.
function sum(a, b) {
return a + b
}
console.log(sum.toString())
//expected output: "function sum(a, b) {
// return a + b
// }
console.log(Math.abs.toString())
//expected output: "function abs() { [native code] }"
Push method adds one or more elements to the end of an array.
const animals = ['pigs', 'goats', 'sheep']
const count = animals.push('cows')
console.log(count)
//expected output: 4
console.log(animals)
//expected output: Array ['pigs', 'goats', 'sheep', 'cows']
animals.push('chickens', 'cats', 'dogs')
console.log(animals)
//expected output: Array ['pigs', 'goats', 'sheep', 'cows', 'chickens', 'cats', 'dogs']
The pop method changes the length of the array. It removes the last element and returns that element.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']
console.log(plants.pop())
//expected output: 'tomato'
console.log(plants)
//expected output: Array ['broccoli', 'cauliflower', 'cabbage', 'kale']
plants.pop()
console.log(plants)
//expected output: ['broccoli', 'cauliflower', 'cabbage']
The reverse method reverses an array in place. The first array element becomes the last, and the last becomes the first.
const array1 = ['one', 'two', 'three']
console.log('array1:', array1)
//expected output: 'array1:" Array ["one", "two", "three"]
const reversed = array1.reverse()
console.log('reversed:', reversed)
//expected output: "reversed:" Array ["three", "two", "one"]
//careful reverse is destructive -- it changes the original array
console.log('array1:', array1)
//expected output: "array1:" Array ["three", "two", "one"]
The indexOf method returns the index within the calling string object of the first occurrence of the specified value.
const str = 'Brawe new world'
console.log('Index of first w from start is ' + str.indexOf('w)) //logs- 8
console.log('Index of "new" from start is ' + str.indexOf('new')) //logs- 6
Also learn, How To Use JavaScript Date() Object, Fast and Easy
The search method executes a search for a match between a regular expression and the string object.
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'
//any character that is not a word character or whitespace
const regex = /[^\w\s]/g
console.log(paragraph.search(regex))
/expected output: 43
console.log(paragraph[paragraph.search(regex)])
//expected output: "."
The replace method returns a new string with some or all matches of a pattern replaced by a replacement.
let str = 'Twas the night before Xmas...'
let newstr = str.replace(/xmas/i, 'Christmas')
console.log(newstr) //Twas the night before Christmas
Join method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string.
const elements = ['fire', 'air', 'water']
console.log(elements.join())
//expected output: "fire,air,water
console.log(elements.join(''))
//expected output l: "fireairwater"
console.log(elements.join('-'))
//expected output: "fire-air-water
That’s it for this post guys. These are the 4 simplest ways through which you can convert array to string in javascript. I hope you liked this article and learned something new from this article. Make sure to leave a comment below.
Also Read: Latest JavaScript Features Every Web Developer Should Know
For a detailed guide on above listed 4 methods please refer to the below pages:
Want more content like this Click Here
[…] Convert Array to String in JavaScript – 4 Easy Methods March 6, 2022 […]