Does Javascript have something like% d?

Here is what I used in NSString ...

[NSString stringWithFormat:@"This is a digit %d", 10];

the value 10 will go to% d .... and the line will become "This is the number 10", is there something similar in javascript? Thank you ... Also, I would like to know what this call is?

+5
source share
8 answers

No built-in string formatting, but you can use a JavaScript library to do the same thing sprintf().

+4
source

You can easily concatenate strings in Javascript:

  var str = "This is a digit " + 10;
+4
source

, :

"This is a digit " + 10;

, , javascript-printf-string-format.

+2

javascript , printf.

+1

bob.js JS framework :

var sFormat = "My name is {0} and I am version {1}.0.";
var result = bob.string.formatString(sFormat, "Bob", 1);
console.log(result);
//output:
//==========
// My name is Bob and I am version 1.0.

-

0

sprintf, . angular, , , .

https://gist.github.com/jakobloekke/7303217

angular.module('filters')
     .filter('sprintf', function() {

    function parse(str) {
        var args = [].slice.call(arguments, 1),
            i = 0;

        return str.replace(/%d/g, function() {
            return args[i++];
        });
    }

    return function() {
        return parse(
            Array.prototype.slice.call(arguments, 0,1)[0], 
            Array.prototype.slice.call(arguments, 1)
        );
    };
});

:

$filter('sprintf')(
    "Hello %d. It %d nice to see you!",
    "World",
    "very"
);

scope.values = ["World", "very"];

<p ng-bind="message | sprintf: values"></p>
0

, . :

var message = "Hello world"
console.log(`This is my message: ${message}. Don't you love it?`)

Template literals are identified by `` defining them and using $ {var} to include variables.

0
source

All Articles