Search code examples
javascriptescapingquotes

Escape quotes on string javascript


I have a variable with this kind of string: 4.5"x8.5"x0.5"

I found many answers about how to escape the quotes, so I write this function:

function replaceQuotesChars (str)
{
    var s = str.trim();

    // s.replace('"','"');

    // s.replace('"','\\"');

    // s.replace(/\"/g,'\\"');

    s.replace(/\"/g,'"');

    return s;
};

But none of those help me to escape the quotes because I get the same string that I submit to the function.

I save that variable with a stringify object to the database so when I parse back the string I get an error.

What I'm doing wrong? Please help me.


Solution

  • After a .replace (or really just about any other string manipulation method) a new string is returned because strings are "immutable" objects (can't be modified once created). Your code assumes the operation happens "in-place". You need to capture the new string (which incidentally, you did do with the .trim() operation).

    In the following code:

    1. First .trim() is called on str, which copies the string in str but without the leading and trailing spaces, and then returns that new string.
    2. On that new string, .replace() is called, which copies the trimmed string, but with the characters replaced and then returns a new string.
    3. That final string is what is then returned by the function.

    function replaceQuotesChars (str, delimeter) {
      // Each string operation returns a new string. Take that final
      // string and return it
      return str.trim().replace(/\"/g, delimeter);
    };
    
    console.log(replaceQuotesChars('10.5" x 4.75"', """));
    console.log(replaceQuotesChars('10.5" x 4.75"', "\'"));
    console.log(replaceQuotesChars('10.5" x 4.75"', "\""));