convert object to string without quotes

JavaScript Convert Object to String Without Quotes

Often web developers convert JavaScript objects to JSON so that they can be passed to web server. They generally use JSON.stringify() method for this purpose, as it is supported by most modern web browsers. While doing so it adds double quotes around all keys and values in your JavaScript object. But sometimes you may need to convert object to string without quotes. In this article, we will learn how to do this using JavaScript.


JavaScript Convert Object to String Without Quotes

Let us say you have the following JavaScript object.

var test = { name: "John Smith" };

When you call JSON.stringify() method on this object, you get the following JSON string.

var json = JSON.stringify(test);
console.log(json); // '{ "name": "John Smith" }'

But sometimes, you may need to convert the above JavaScript object to the following.

'{ name: "John Smith" } '

This may be because the system receiving this JSON data has been wrongly configured or uses incorrect JSON format. You can do this using replace() function along with a regular expression as shown below.

var unquoted = json.replace(/"([^"]+)":/g, '$1:');
console.log(unquoted);  // {name:"John Smith"}

Let us look at the above code in detail. We have used regular expression “([^”]+)”: above. We also use backreference $1 to make sure that only the quotes around keys are replaced and not those around properties.

You can customize the regular expression as per your requirement.

In this article, we have learnt how to convert object to string.

Also read:

How to Highlight Text Using JavaScript
How to Check File MIME Type With JS
How to Replace Line Breaks With Br Tag
How to Detect When User Leaves Web Page
How to Generate PDF from HTML using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *