Does Javascript have something like %d?
Here is something I used in NSString ...
[NSString stringWithFormat:@"This is a digit %d", 10];
the 10 value will go to %d...., and the string will beco开发者_运维知识库me "This is a digit 10", is there any similar thing in javascript? Thank you... Also, I would like to know, what is this call??
There is no built-in string formatting, but you can use a JavaScript library to do the same: sprintf()
.
You can concatenate strings easily in Javascript:
var str = "This is a digit " + 10;
To achieve the same effect, you can just say:
"This is a digit " + 10;
Alternatively, if you need actual string formatting you may want to have a look at javascript-printf-string-format.
There is no such thing in javascript but you can build your own printf.
This is possible using regular expressions.
http://www.regular-expressions.info/javascript.html This is a fairly good website for the topic, refer to the section 'Replacement Text Syntax'.
bob.js JS framework allows doing this:
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.
- Tengiz
Here's a simple sprintf implementation I found. It's built as an angular filter but the logic can of course be pulled out.
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)
);
};
});
Usage:
$filter('sprintf')(
"Hello %d. It's %d nice to see you!",
"World",
"very"
);
or
scope.values = ["World", "very"];
<p ng-bind="message | sprintf: values"></p>
Nowadays, we have template strings, which accomplish a very similar thing. They work like this:
var message = "Hello world"
console.log(`This is my message: ${message}. Don't you love it?`)
Template literals are identified by the `` defining them and using ${var} to include variables.
精彩评论