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".
Author by
DEVOPS
Updated on July 25, 2022Comments
-
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 almost 9 yearsThis is destructive replacement.
-
Reeebuuk about 8 yearsif anybody need to escape the single quotes inside and '\'' doesn't work try with text.replace(/'/g, "‘");
-
Parth Savadiya almost 6 yearswhat is the meaning of /g?
-
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