How do I put variables inside javascript strings?

前端 未结 13 1116
感动是毒
感动是毒 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 16:05

    A few ways to extend String.prototype, or use ES2015 template literals.

    var result = document.querySelector('#result');
    // -----------------------------------------------------------------------------------
    // Classic
    String.prototype.format = String.prototype.format ||
      function () {
        var args = Array.prototype.slice.call(arguments);
        var replacer = function (a){return args[a.substr(1)-1];};
        return this.replace(/(\$\d+)/gm, replacer)
    };
    result.textContent = 
      'hello $1, $2'.format('[world]', '[how are you?]');
    
    // ES2015#1
    'use strict'
    String.prototype.format2 = String.prototype.format2 ||
      function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); };
    result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]');
    
    // ES2015#2: template literal
    var merge = ['[good]', '[know]'];
    result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;

提交回复
热议问题