0

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.

junihh
  • 502
  • 1
  • 9
  • 25

2 Answers2

4

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"', "\""));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

@Scott Marcus has already answered the question but if you are confused using regex(like me) there is an alternate method using the .split() method.

var a = str.split("\"");
var newS=""
for(var i = 0; i<a.length; i++){
    if(a[1]!= ""){
        newS = newS + a[i];
    }
}
return newS;

This runs slower than regex but does the job.

JustCurious
  • 780
  • 1
  • 10
  • 29