Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Last active July 16, 2023 19:06
Show Gist options
  • Save MirzaLeka/fe33f850d783997181d97dc02cefc000 to your computer and use it in GitHub Desktop.
Save MirzaLeka/fe33f850d783997181d97dc02cefc000 to your computer and use it in GitHub Desktop.
Replace double quotes with single quotes | Javascript

Replace Double Quotes with Single ones in JavaScript

During my short use of MongoDB I encountered an issue with double quotes. Since MongoDB stores documents (objects) as JSON fields, key and value pairs, all string values are surrounded with double quotes. Example:

{"name": "Bruce Wayne"}

Although MongoDB will add an escape character if you use double quotes, using double quotes multiple times in the same string will throw an error. To avoid it, I found this handy code snippet that will replace all double quotes with single ones using regex.

Example:

var text = "I'm "Batman" and I'm "Awesome"!"
text = text.replace(/"/g, "'");

console.log(text);

Output:

'I'm 'Batman' and I'm 'Awesome'!'

Source: StackOverFlow
Author: amit_g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment