coder
coder

Reputation: 4283

How do I replace single quotes with double quotes in JavaScript?

The following code replaces only one single quote:

var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace("'", "\"");
console.log(b);

Upvotes: 57

Views: 155407

Answers (8)

The Jared Wilcurt
The Jared Wilcurt

Reputation: 340

The other answers given on this post don't handle edge cases very well. For example, if your string contains inner strings with escaped single quotes:

/**
 * Swaps single quotes for double quotes, retaining escaped single quotes.
 *
 * @param  {string} str  Input
 * @return {string}      Swapped output
 */
function replaceSingleQuotesWithDoubleQuotes (str) {
  return str
    .replaceAll('\\\'', '__ESCAPED_SINGLE_QUOTE__')
    .replaceAll('\'', '"')
    .replaceAll('__ESCAPED_SINGLE_QUOTE__', '\\\'');
}

const value = `['Cat\\'s', 'Dog\\'s']`;
// `["Cat\\'s", "Dog\\'s"]`
const result = replaceSingleQuotesWithDoubleQuotes(value);

Alternatively, if you just want to swap all single/double quotes:

/**
 * Swaps single and double quotes
 *
 * @param  {string} str  Input
 * @return {string}      Swapped output
 */
function swapQuotes (str) {
  return str.replace(/[\'\"]/g, function (match) {
    return match === '"' ? '\'' : '"';
  });
}

const value = `{ "value": ['Cat', 'Dog'] }`;
// `{ 'value': ["Cat", "Dog"] }`
const result = swapQuotes(value);

Hi future me :)

Upvotes: 0

Raz
Raz

Reputation: 444

replaceAll(search, replaceWith) replaces ALL occurrences of search with replaceWith.

Then, make sure you have a string by wrapping one type of qoutes by different type:

 "a 'b' c".replaceAll("'", '"')
 // result: "a "b" c"
    
 "a 'b' c".replaceAll(`'`, `"`)
 // result: "a "b" c"

More about replaceAll

replaceAll (MDN): replaceAll(search, replaceWith)

It's actually the same as using replace() with a global regex(*), merely replaceAll() is a bit more readable in my view.

(*) Meaning it'll match all occurrences.


Example 1 - search with a string

const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.' 
   
console.log(p.replaceAll('2020', '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."

Example 2 - search with regex

const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'    
const regex = /2020/gi


console.log(p.replaceAll(regex, '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".


You can also use a function as replaceWith

In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

Upvotes: 5

RafH
RafH

Reputation: 4544

var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/'/g, '"');
console.log(b);

Edit: Removed \ as there are useless here.

Upvotes: 130

yckart
yckart

Reputation: 33378

You can use a RegExp with the global flag g and all quotes will replaced:

var b = a.replace(/'/g, '"');

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

This looks suspiciously like bad JSON, so I suggest using actual array and object literals, then encoding the proper way:

var a = [{'column1':'value0','column2':'value1','column3':'value2'}];
var b = JSON.stringify(a);

Upvotes: 3

RaphaelDDL
RaphaelDDL

Reputation: 4480

Need to use regex for this:

var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/\'/g, "\"");

http://jsfiddle.net/9b3K3/

Upvotes: 9

sebnukem
sebnukem

Reputation: 8303

Add the g modifier: var b = a.replace(/'/g, '"');

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

You can use a global qualifier (a trailing g) on a regular expression:

var b = a.replace(/'/g, '"');

Without the global qualifier, the regex (/'/) only matches the first instance of '.

Upvotes: 6

Related Questions