How to convert an array of strings in double quotes to array of strings in single quotes in JavaScript
Welcome to DevMaesters! In this post, I will show you how to convert an array of strings in double quotes to the same array of strings but this time in single quotes.
Let's say we have a sample array like this:
let sample = ["a1", "a2", "a3", "a4"]
Note that this is the default format for arrays created using either [ ] or newArray
To convert it to an array with single quotes, you just have to follow the steps below:
Step 1: First, convert the array to a string format using JSON.stringify, as shown below:
// Convert the array to a string using JSON.stringify
let jsonString = JSON.stringify(sample);
Step 2: Replace every instance of double quotes with single quotes using the replace method:
// Replace every instance of double quotes with single quotes using the replace method
let singleQuoteString = jsonString.replace(/"/g, "'");
Step 3: Recreate a parseable array
singleQuoteString = `"[${singleQuoteString.slice(1, -1)}]"`
Step 4: Convert the single quote string back to an array using JSON.parse:
// Convert the single quote string back to an array using JSON.parse
let singleQuoteArray = JSON.parse(singleQuoteString);
When you console.log the result, you should expect an array like the one below:
console.log("Result: ", singleQuoteArray);
// Expected result:
// Result: ['a1', 'a2', 'a3', 'a4']
That's all for this post. Thanks for reading! Feel free to leave a comment down below if you have any questions or run into any issues concerning the steps in the post.