Replacing a string in Javascript while keeping JSON file intact

Viewed 970

I am working with a Discord bot and have a JSON file called config.json that looks like this:

{
"token": "stuff"
"prefix": "!"
}

And I want to replace the "prefix: "!" line. My code is this:

if(cmd == "prefix"){
    var new_prefix = "\"prefix\": " + "\"" + String(args[0]) + "\"";
    var data = fs.readFileSync("config.json", "utf-8");
    var newValue = data.replace(/"prefix"\s*:\s*".+"/gm, "new_prefix");
    fs.writeFileSync("config.json", new_prefix, "utf-8");
};

Instead of only replacing the one line, it overwrites my entire config.JSON file so that after it looks like this:

"prefix":"stuffHere"

How can I make it only replace the one line and left the rest of the file intact?

1 Answers

Don't use regex for that, that makes things a whole lot more complicated than they need to be. Use JSON.parse to turn the JSON string into an object, assign to the prefix property on the object, and then write the stringified object:

if(cmd == "prefix"){
    var dataJSON = fs.readFileSync("config.json", "utf-8");
    var data = JSON.parse(dataJSON);
    data.prefix = "new_prefix";
    fs.writeFileSync("config.json", JSON.stringify(data), "utf-8");
}

If you had to use a regular expression for that, for whatever reason, then you would have to replace the "prefix": "<oldvalue>" with not only the new value, but with the prefix property as well. When matching the value (starts with "), lazy-repeat any character until you get to another ", if the string doesn't contain double quotes as well:

.replace(/"prefix": *".*?"/, '"prefix": "new prefix"')

https://regex101.com/r/zyhPqG/1

Related