简体   繁体   中英

How to remove double quote from a string in JavaScript

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.

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 ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM