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

前端 未结 13 2057
轻奢々
轻奢々 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
    2020-12-07 11:28

    Here is another way of doing this by using es6 template literals dynamically at runtime.

    const str = 'My name is ${name} and my age is ${age}.'
    const obj = {name:'Simon', age:'33'}
    
    
    const result = new Function('const {' + Object.keys(obj).join(',') + '} = this.obj;return `' + str + '`').call({obj})
    
    document.body.innerHTML = result

提交回复
热议问题