How do I put variables inside javascript strings?

前端 未结 13 1118
感动是毒
感动是毒 2020-12-12 15:12
s = \'hello %s, how are you doing\' % (my_name)

That\'s how you do it in python. How can you do that in javascript/node.js?

13条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 15:50

    I wrote a function which solves the problem precisely.

    First argument is the string that wanted to be parameterized. You should put your variables in this string like this format "%s1, %s2, ... %s12".

    Other arguments are the parameters respectively for that string.

    /***
     * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
     * @return "my name is John and surname is Doe"
     *
     * @firstArgument {String} like "my name is %s1 and surname is %s2"
     * @otherArguments {String | Number}
     * @returns {String}
     */
    const parameterizedString = (...args) => {
      const str = args[0];
      const params = args.filter((arg, index) => index !== 0);
      if (!str) return "";
      return str.replace(/%s[0-9]+/g, matchedStr => {
        const variableIndex = matchedStr.replace("%s", "") - 1;
        return params[variableIndex];
      });
    }
    

    Examples

    parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
    // returns "my name is John and surname is Doe"
    
    parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
    // returns "this method sooo goood"
    

    If variable position changes in that string, this function supports it too without changing the function parameters.

    parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
    // returns "i have 5 books and 6 pencils."
    

提交回复
热议问题