0

I am trying to remove the double quotes inside the string but was not able to do so.

var productName = "300" Table";
console.log(productName);
var newTemp = productName.replace('"', /'/g);
console.log(newTemp);
var requestData = JSON.stringify({
        'product_name': productName,
        'page_url': newTemp
    });

var obj = JSON.parse(requestData);
console.log(obj);

It is throwing an error in the second line.

4
  • 1
    If you are trying to make a test case you need to put a \ in front of the " after 300 Commented May 17, 2018 at 16:43
  • 1
    Read the documentation for replace one more time, a little more carefully. Read the documentation for string literals one more time, a little more carefully. Also, why are you stringifying the object, and then immediately parsing it again? Commented May 17, 2018 at 16:43
  • You could split string on double quote and then join it back.. Or you could use urlEncode to encode a double quote, replace the encoded double quote, then decide the string back.. Commented May 17, 2018 at 16:47
  • var productName = "300" Table"; is a syntax error. It makes it hard to help you when we don't know for sure what your actual starting point (the actual string) is. Commented May 28, 2019 at 17:45

1 Answer 1

1

From your coding pattern I think you need something like this just escape the inner double quotes(") with a slash(\) when you assign string to productName variable. Then replace the occurrence of double quotes with nothing i.e productName.replace(/"/g, "")

Full Code: Shorten after removing unnecessary JSON.stringify() & JSON.parse()

var productName = "300\" Table";
var newTemp = productName.replace(/"/g, "");
console.log(`old productName = ${productName}, newTemp after replace " = ${newTemp}`);
var requestData = {
  'product_name': productName,
  'page_url': newTemp
};
console.log(requestData );

See Escape notation on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.