Reputation: 18790
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, "'");
Upvotes: 53
Views: 140320
Reputation: 444
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".
Upvotes: 5
Reputation: 31250
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
Upvotes: 138