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

前端 未结 13 2079
轻奢々
轻奢々 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:36

    You can use JQuery(jquery.validate.js) to make it work easily.

    $.validator.format("My name is {0}, I'm {1} years old",["Bob","23"]);
    

    Or if you want to use just that feature you can define that function and just use it like

    function format(source, params) {
        $.each(params,function (i, n) {
            source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
        })
        return source;
    }
    alert(format("{0} is a {1}", ["Michael", "Guy"]));
    

    credit to jquery.validate.js team

提交回复
热议问题