jacobytes
jacobytes

Reputation: 3241

Replace double quotes with graves in a string without creating a new string

I have a json in which I store a property with a link. I want to write this to a .txt file so I can copy the content and use it in a resource object which has a serverUrl variable that I want to inject using template literals. Before I can do that I need to change the string value of the JSON a bit so I can use the template literals.

The json object has the following format:

{
  "products": [
    {
      "image": "http://test.test.com/images/imageName.jpg"
    },
    {
      "image": "http://test.test.com/images/imageName2.jpg"
    }
  ]
}

What I am trying to achieve is to change every image value to the following format for each product object:

`http://${serverUrl}/images/imagename`

I managed to replace the url using a simple string.replace() during the json creation, but I am struggling with the following steps:

  1. Change the double quotes to graves ("" => ``) and keep the url.
  2. Do it globaly, I don't want to extract the values, the object should be overwritten.

I've tried writing some regexes, but I can't seem to figure out how I can replace both the double quotes and keep the url in one regex. Is this the right way to go about this? Or should I try something completely different

Edit

My code so far

let dataImport = [];

// Code to convert excel to JSON
// Contains the following line for the image property
case "image": 
  value = value.replace("https://test.test.com", "${serverUrl}");
  rowData["image"] = value;
break;

// Convert object
let json = JSON.stringify(dataImport, null, 2);
fs.writeFileSync("data.txt", json);

Upvotes: 0

Views: 223

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89171

var json = JSON.stringify({
  "products": [
    {
      "image": "http://test.test.com/images/imageName.jpg"
    },
    {
      "image": "http://test.test.com/images/imageName2.jpg"
    }
  ]
}, null, '  ');

var domain = "test.test.com";
console.log(convertJsonUrls(json, domain));

/**
 * Converts any strings containing urls for the specified domain into template-strings,
 * and replaces the domain with '${serverUrl}'
 */
function convertJsonUrls(json, domain) {
    var stringRE = /"((?:\\.|[^\\"])*)"/g;
    var urlRE = new RegExp("^(https?://)" + escapeRegExp(domain) + "(/.*)$");

    var template = json.replace(stringRE, function (raw, content) {
        var urlMatch = urlRE.exec(content);
        if (!urlMatch) return raw; // no change, keep double-quotes
        return "`" + urlMatch[1] + "${serverUrl}" + urlMatch[2] + "`";
    });

    return template;
}

/**
 * Escapes any RegExp special characters.
 * Copied from https://stackoverflow.com/a/6969486/22364
 */
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Upvotes: 1

Related Questions