1

I have this template:

var temp = "<div class="${class}" id="loc" data-res="${res}"></div>";

and i would like to replace ${res} with an array, so I can later do something like that:

$('#loc').data('res');

I tried this:

var res = [["a","b"],["c","d"]];
var arr = { class: "bold", res: res};
var newtemp = rep(temp, arr);

function rep(temp, arr) 
        {
            return temp.replace(/\$\{([\w]+)\}/g, function(s1, s2) { 
                var s = arr[s2]; 
                if (typeof (s) != "undefined"){ 
                    return s; 
                } else { 
                    return s1; } 
            });
        }

But no way... for the ${res} sustitution and keep formated like an array. I would like this result:

<div class="bold" id="loc" data-res='[["a","b"],["c","d"]]'></div>

1 Answer 1

1

You can check if the variable s is an array and then use JSON.stringify() to keep the array in the string format as you want.

But you temp variable has some issue. It contains double quotes inside double quotes. And in your expected result example, you use both double quotes and single quotes. So I suggest changing the temp variable to:

var temp = `<div class="$class" id="loc" data-res='$res'></div>`;

And change the regex you're using a bit. The final rep function will be:

function rep(temp, arr) {
    return temp.replace(/\$([\w]+)/g, function (s1, s2) {
        var s = arr[s2];
        if (typeof (s) != "undefined") {
            return Array.isArray(s) ? JSON.stringify(s) : s;
        } else {
            return s1;
        }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.