I need a way to replace ‘ with ‘ on a string, I tried:
value = 'I'm now spending. I'll also be holding'
value = value.replace(/'/g,"\'");
-------------------------------------------------
output: I\'m now spending. I\'ll also be holding
value = 'I'm now spending. I'll also be holding'
value = value.replace(/'/g,"'");
---------------------------------------------
output: I'm now spending. I'll also be holding
I need the output to be I'm now spending. I'll also be holding
2
Answers
If you want to replace single quotes with escaped single quotes (i.e.,
'
with'
), you can use the following JavaScript code:This will produce the desired output:
In this code,
value.replace(/'/g, "\'")
searches for all occurrences of single quotes (/'/g
) and replaces them with\'
, where\
is the escape sequence for a single backslash and'
is the escaped single quote.Remember that when you print the string to the console, it might not show the backslashes because the backslash is an escape character in string literals. The actual value of
value
will be what you want.If you whant to replace the first
'
with'
in your string, you can use regexp and do:but you only replace the first one
'
.Regarding your use case I would advise you to use ‘replaceAll’ to replace each iteration
If you are unsure about a regex, you can use a test environment like "regex101"