skip to Main Content

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


  1. If you want to replace single quotes with escaped single quotes (i.e., ' with '), you can use the following JavaScript code:

    let value = 'I'm now spending. I'll also be holding';
    value = value.replace(/'/g, "\'");
    console.log(value);
    

    This will produce the desired output:

    I'm now spending. I'll also be holding
    

    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.

    Login or Signup to reply.
  2. If you whant to replace the first ' with ' in your string, you can use regexp and do:

    str = "I'm now spending. I'll also be holding";
    str.replace(/[']/gm, "\'");
    

    but you only replace the first one '.

    Regarding your use case I would advise you to use ‘replaceAll’ to replace each iteration

    str = "I'm now spending. I'll also be holding";
    str.replaceAll(/[']/gm, "\'");
    

    If you are unsure about a regex, you can use a test environment like "regex101"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search