remove quotes from array javascript

How to Remove Quotes from Array in JavaScript

As a developer, I have often found myself in situations where I need to remove quotes from an array in JavaScript. There are several ways to do this, and in this article, I will share a few methods that I have personally used.

Method 1: Using the map() method

The map() method creates a new array with the results of calling a provided function on every element in the calling array. We can use this method to remove quotes from an array in JavaScript.


let arr = ['"hello"', '"world"', '"javascript"'];
arr = arr.map(function(str) {
    return str.replace(/["']/g, "");
});
console.log(arr);
// Output: ["hello", "world", "javascript"]

In the above code, we first define the array with quotes. We then use the map() method to loop through each element of the array and remove the double quotes using the replace() method. We use a regular expression to replace all occurrences of double quotes in the string. Finally, we assign the modified array back to our original array variable and log it to the console.

Method 2: Using the forEach() method

The forEach() method is another way to loop through an array and modify its elements. We can use this method to remove quotes from an array in JavaScript.


let arr = ['"hello"', '"world"', '"javascript"'];
arr.forEach(function(str, index) {
    arr[index] = str.replace(/["']/g, "");
});
console.log(arr);
// Output: ["hello", "world", "javascript"]

In this example, we first define the array with quotes. We then use the forEach() method to loop through each element of the array and remove the double quotes using the replace() method. We use a regular expression to replace all occurrences of double quotes in the string. Finally, we log the modified array to the console.

Method 3: Using the filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. We can use this method to remove quotes from an array in JavaScript.


let arr = ['"hello"', '"world"', '"javascript"'];
arr = arr.filter(function(str) {
    return str !== '"';
});
console.log(arr);
// Output: ["hello", "world", "javascript"]

In this example, we first define the array with quotes. We then use the filter() method to create a new array with all elements that do not equal a double quote. Finally, we assign the modified array back to our original array variable and log it to the console.

These are just a few methods that can be used to remove quotes from an array in JavaScript. Depending on the specific use case, one method may be more suitable than another. It's always a good idea to experiment with different methods and choose the one that works best for your situation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe