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.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.