mediocre
mediocre

Reputation: 564

Replace multiple values in file loop

I'm trying to build a quick and dirty static site generator for myself.

Let's say I have this test.html file:

{title}
{downloadpath}

This is my current.json where I get the values i want to replace:

{
    "id": 123,
    "album" : [{
        "title": "Test EP",
        "albumid": 1234,
        "path": "test.zip"
     }]
}

My replacement function looks like this:

    // Iterate through JSON object and replace
    function iterate(obj) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object")
                    iterate(obj[property]);
                else
                console.log("replace {" + property + "} with " + obj[property] )
                htmldata.replace(/\{property\}/g, obj[property]);
            }
        }
    }
    iterate(json)
    var result = htmldata

    console.log(result)

    // Write new HTML
    fs.writeFile("test-" + json.id + ".html", result, 'utf8', function (err) {
        if (err) {
            return console.log(err);
        }
    });

and if I run it it works like this:

replace {id} with 123
replace {title} with Test EP
replace {albumid} with 1234
replace {path} with test.zip
{title}
{path}

and you can see the problem right there. I think it's always replacing the edited file with the input file so I don't see any changes. I can't figure it out and if someone could point me in the right direction I'd be grateful.

Thanks!

Upvotes: 0

Views: 305

Answers (1)

Vivin Paliath
Vivin Paliath

Reputation: 95518

Not using braces around your if statements will lead to subtle bugs!

You want:

if (typeof obj[property] == "object") {
    iterate(obj[property]);
} else {
    console.log("replace {" + property + "} with " + obj[property] )
    htmldata.replace(/\{property\}/g, obj[property]);
}

Otherwise the replace will run every time regardless of the condition on the if.

Second thing: your regex tries to match the literal string "{property}". Instead, try this:

htmldata.replace(new RegExp("{" + property + "}", "g"), obj[property]);

Third thing: you're not assigning the result of the replace back to htmldata. So you need to do this:

htmldata = htmldata.replace(new RegExp("{" + property + "}", "g"), obj[property]);

Upvotes: 3

Related Questions