join() Method Syntax
arr.join(separator)
The method takes a parameter in form of a string (as separator). It can be a hyphen, pipe (|), any special character or simply an empty space. You have to specify a string value, which will be used to separate the array values from each other.
The join(), when used with an array, returns a new string concatenated using a specified separator. If there is no separator specified, it will return values with commas.
👉 How to remove empty slots in an Array using a One-Line-Code in JavaScript.
The parameter (or the argument) is optional.
If there is only one value in the array, it will display just that one value without any separator.
It is one of the simplest ways to remove commas from an array in JavaScript.
Now, let’s see how to remove the commas using the array.join() method.
<script>
let removeComma= () => {
let arr = ['alpha', 'bravo', 'charlie'];
document.write (arr.join(' '));
}
removeComma();
</script>
In the above example, the parameter to the join() is a space. Therefore, it will display the array values separated by a space, removing all the commas.
Now, here’s another example, where I am using just an empty string. The commas will be replaced with no space at all.
<script>
let removeComma = () => {
let arr = ['51', '- Lane', 'Worli'];
document.write (arr.join(''));
}
removeComma();
</script>
👉 Arrays can have letters and numbers. How to filter out only numbers in an Array. Check this out.