Format a JavaScript string using placeholders and an object of substitutions?

前端 未结 13 2070
轻奢々
轻奢々 2020-12-07 10:56

I have a string with say: My Name is %NAME% and my age is %AGE%.

%XXX% are placeholders. We need to substitute values there from an object.

13条回答
  •  鱼传尺愫
    2020-12-07 11:28

    You can use a custom replace function like this:

    var str = "My Name is %NAME% and my age is %AGE%.";
    var replaceData = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
    
    function substitute(str, data) {
        var output = str.replace(/%[^%]+%/g, function(match) {
            if (match in data) {
                return(data[match]);
            } else {
                return("");
            }
        });
        return(output);
    }
    
    var output = substitute(str, replaceData);
    

    You can see it work here: http://jsfiddle.net/jfriend00/DyCwk/.

提交回复
热议问题