How to replace all double quotes to single quotes using jquery?

118,911

Solution 1

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

Solution 2

You can also use replaceAll(search, replaceWith) [MDN].

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

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

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

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".

Share:
118,911
DEVOPS
Author by

DEVOPS

Updated on July 25, 2022

Comments

  • DEVOPS
    DEVOPS almost 2 years

    I need to replace all double quotes to single quotes using jquery.

    How I will do that.

    I tested with this code but its not working properly.

    newTemp = newTemp.mystring.replace(/"/g, "'");

  • Alan Dong
    Alan Dong almost 9 years
    This is destructive replacement.
  • Reeebuuk
    Reeebuuk about 8 years
    if anybody need to escape the single quotes inside and '\'' doesn't work try with text.replace(/'/g, "‘");
  • Parth Savadiya
    Parth Savadiya almost 6 years
    what is the meaning of /g?
  • ocramot
    ocramot almost 5 years
    @ParthSavadiya it stands for 'global'. It's a replaceAll, it doesn't stop at the first occurrence. https://javascript.info/regexp-introduction#flags