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

前端 未结 13 2004
轻奢々
轻奢々 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条回答
  • I have written a code that lets you format string easily.

    Use this function.

    function format() {
        if (arguments.length === 0) {
            throw "No arguments";
        }
        const string = arguments[0];
        const lst = string.split("{}");
        if (lst.length !== arguments.length) {
            throw "Placeholder format mismatched";
        }
        let string2 = "";
        let off = 1;
        for (let i = 0; i < lst.length; i++) {
            if (off < arguments.length) {
                string2 += lst[i] + arguments[off++]
            } else {
                string2 += lst[i]
            }
        }
        return string2;
    }
    

    Example

    format('My Name is {} and my age is {}', 'Mike', 26);
    

    Output

    My Name is Mike and my age is 26

    0 讨论(0)
提交回复
热议问题