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

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

    Currently there is still no native solution in Javascript for this behavior. Tagged templates are something related, but don't solve it.

    Here there is a refactor of alex's solution with an object for replacements.

    The solution uses arrow functions and a similar syntax for the placeholders as the native Javascript interpolation in template literals ({} instead of %%). Also there is no need to include delimiters (%) in the names of the replacements.

    There are two flavors: descriptive and reduced.

    Descriptive solution:

    const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
    
    const replacements = {
      name: 'Mike',
      age: '26',
    };
    
    const string = stringWithPlaceholders.replace(
      /{\w+}/g,
      placeholderWithDelimiters => {
        const placeholderWithoutDelimiters = placeholderWithDelimiters.substring(
          1,
          placeholderWithDelimiters.length - 1,
        );
        const stringReplacement = replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters;
        return stringReplacement;
      },
    );
    
    console.log(string);

    Reduced solution:

    const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
    
    const replacements = {
      name: 'Mike',
      age: '26',
    };
    
    const string = stringWithPlaceholders.replace(/{\w+}/g, placeholder =>
      replacements[placeholder.substring(1, placeholder.length - 1)] || placeholder,
    );
    
    console.log(string);

提交回复
热议问题