JJ.
JJ.

Reputation: 9970

how to remove double quotes and escape it in specific parts of a string

I have this string:

{
    "QueryString": null,
    "ProjectName": ""24"",
    "SeasonName": "",
    "MemberName": "",
    "CompanyName": "",
    "CompanyRole": 0,
    "CompanyRoles": "",
    "Year": ""
}

I want to make it look like this (FOR ALL VALUES THAT HAVE DOUBLE QUOTES IN THEM -- in this case, only the value of property ProjectName has it) using the replace function:

{
    "QueryString": null,
    "ProjectName": "\"24\"",
    "SeasonName": "",
    "MemberName": "",
    "CompanyName": "",
    "CompanyRole": 0,
    "CompanyRoles": "",
    "Year": ""
}

How do I go about doing this in JavaScript?

Upvotes: 1

Views: 112

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382464

Use replace with a regular expression :

var str = '{\
    "QueryString": null,\
    "ProjectName": ""24"",\
    "SeasonName": "",\
    "MemberName": "",\
    "CompanyName": "",\
    "CompanyRole": 0,\
    "CompanyRoles": "",\
    "Year": ""\
}';

str = str.replace(/""([^"]*)"",/g,'"\\"$1\\"",');

Upvotes: 2

Related Questions