How to interpolate variables in strings in JavaScript, without concatenation?

前端 未结 16 2271
长情又很酷
长情又很酷 2020-11-22 02:41

I know in PHP we can do something like this:

$hello = \"foo\";
$my_string = \"I pity the $hello\";

Output: \"I pity the foo\"<

相关标签:
16条回答
  • 2020-11-22 02:58

    Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:

    var hello = "foo";
    var my_string = sprintf("I pity the %s", hello);
    
    0 讨论(0)
  • 2020-11-22 03:00

    I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

    var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
    

    which will replace the {0} and {1} with the array items and return the following string

    "this is a test string for stringInject"
    

    or you could replace placeholders with object keys and values like so:

    var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
    
    "My username is tjcafferkey on Github" 
    
    0 讨论(0)
  • 2020-11-22 03:01

    You can take advantage of Template Literals and use this syntax:

    `String text ${expression}`
    

    Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.

    This feature has been introduced in ES2015 (ES6).

    Example

    var a = 5;
    var b = 10;
    console.log(`Fifteen is ${a + b}.`);
    // "Fifteen is 15.
    

    How neat is that?

    Bonus:

    It also allows for multi-line strings in javascript without escaping, which is great for templates:

    return `
        <div class="${foo}">
             ...
        </div>
    `;
    

    Browser support:

    As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.


    Side note:

    Starting from IE8+ you can use basic string formatting inside console.log:

    console.log('%s is %d.', 'Fifteen', 15);
    // Fifteen is 15.
    
    0 讨论(0)
  • 2020-11-22 03:01

    Create a method similar to String.format() of Java

    StringJoin=(s, r=[])=>{
      r.map((v,i)=>{
        s = s.replace('%'+(i+1),v)
      })
    return s
    }
    

    use

    console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
    
    0 讨论(0)
  • 2020-11-22 03:03

    well you could do this, but it's not esp general

    'I pity the $fool'.replace('$fool', 'fool')
    

    You could easily write a function that does this intelligently if you really needed to

    0 讨论(0)
  • 2020-11-22 03:04

    Complete answer, ready to be used:

     var Strings = {
            create : (function() {
                    var regexp = /{([^{]+)}/g;
    
                    return function(str, o) {
                         return str.replace(regexp, function(ignore, key){
                               return (key = o[key]) == null ? '' : key;
                         });
                    }
            })()
    };
    

    Call as

    Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
    

    To attach it to String.prototype:

    String.prototype.create = function(o) {
               return Strings.create(this, o);
    }
    

    Then use as :

    "My firstname is ${first}".create({first:'Neo'});
    
    0 讨论(0)
提交回复
热议问题