我有一个网址,我想替换部分内容,具体取决于我正在制作的电话。
例如,我的网址格式为
var url = "http://www.example.com/server/32/users/255667753/images/233.jpg"
我想调用同一表单的不同网址,但只更改了数字。目前,我正在这样做
var urlPart1 = "http://www.example.com/server/"
var urlPart2 = "/users/";
var urlPart3 = "/images/";
var urlPart4 = ".jpg";
var sendRequestTo = urlPart1 + 32 + urlPart2 + 255667753 + urlPart3 + 233 + urlPart4.
然而,是否有更好的方法,就像在Java中一样?
答案 0 :(得分:2)
您可以使用regexp
String.prototype.format = function() {
var regexp = /\{(\d+)\}/g, values = arguments;
return this.replace(regexp, function(match, index) {
return values[index];
});
};
var server = "http://www.example.com";
console.log("{0} is {1}".format("a", "b"));
console.log("{3}/server/{0}/users/{1}/images/{2}.jpg".format(32, 255667753, 233, server));
这种方法更像是c#,但它允许你以任何顺序放置参数。
答案 1 :(得分:1)
Declare this function globally somewhere
String.prototype.format = function (args) {
var newStr = this;
for (var key in args) {
newStr = newStr.replace('{' + key + '}', args[key]);
}
return newStr;
}
// This is generic url that will be formatted on the fly with dynamic numbers
var url = "http://www.example.com/server/{serverNo}/users/{userNo}/images/{imgNo}.jpg"
// call it with your dynamic numbers
url = url.format({serverNo:230948,userNo:123897,imgNo:1239378});
And finally your url will become
"http://www.example.com/server/230948/users/123897/images/1239378.jpg"
Happy coding.. :)
答案 2 :(得分:1)
由于TypeScript更多地面向面向对象编程,我们需要扩展接口。我们需要扩展String接口,然后我们需要提供一个实现:
interface String {
format(...replacements: string[]): string;
}
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
您可以通过这种方式随处使用:
var myStr = 'This is an {0} for {0} purposes: {1}';
alert(myStr.format('example', 'end'));
干杯!