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

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

    As a quick example:

    var name = 'jack';
    var age = 40;
    console.log('%s is %d yrs old',name,age);
    

    The output is:

    jack is 40 yrs old

    0 讨论(0)
  • 2020-12-07 11:37

    This allows you to do exactly that

    NPM: https://www.npmjs.com/package/stringinject

    GitHub: https://github.com/tjcafferkey/stringinject

    By doing the following:

    var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
    
    // My username is tjcafferkey on Git
    
    0 讨论(0)
  • 2020-12-07 11:38

    Just use replace()

    var values = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
    var substitutedString = "My Name is %NAME% and my age is %AGE%.".replace("%NAME%", $values["%NAME%"]).replace("%AGE%", $values["%AGE%"]);
    
    0 讨论(0)
  • 2020-12-07 11:38

    If you want to do something closer to console.log like replacing %s placeholders like in

    >console.log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright")
    >Hello Loreto how are you today is everything allright?
    

    I wrote this

    function log() {
      var args = Array.prototype.slice.call(arguments);
      var rep= args.slice(1, args.length);
      var i=0;
      var output = args[0].replace(/%s/g, function(match,idx) {
        var subst=rep.slice(i, ++i);
        return( subst );
      });
       return(output);
    }
    res=log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright");
    document.getElementById("console").innerHTML=res;
    <span id="console"/>

    you will get

    >log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright")
    >"Hello Loreto how are you today is everything allright?"
    

    UPDATE

    I have added a simple variant as String.prototype useful when dealing with string transformations, here is it:

    String.prototype.log = function() {
        var args = Array.prototype.slice.call(arguments);
        var rep= args.slice(0, args.length);
        var i=0;
        var output = this.replace(/%s|%d|%f|%@/g, function(match,idx) {
          var subst=rep.slice(i, ++i);
          return( subst );
        });
        return output;
       }
    

    In that case you will do

    "Hello %s how are you %s is everything %s?".log("Loreto", "today", "allright")
    "Hello Loreto how are you today is everything allright?"
    

    Try this version here

    0 讨论(0)
  • 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);

    0 讨论(0)
  • 2020-12-07 11:49
    const stringInject = (str = '', obj = {}) => {
      let newStr = str;
      Object.keys(obj).forEach((key) => {
        let placeHolder = `#${key}#`;
        if(newStr.includes(placeHolder)) {
          newStr = newStr.replace(placeHolder, obj[key] || " ");
        }
      });
      return newStr;
    }
    
    Input: stringInject("Hi #name#, How are you?", {name: "Ram"});
    Output: "Hi Ram, How are you?"
    
    0 讨论(0)
提交回复
热议问题