这是我的代码
$http.get("/Student/GetStudentById?studentId=" + $scope.studentId + "&collegeId=" + $scope.collegeId)
.then(function (result) {
});
在上面的代码中使用http服务来获取基于id的学生详细信息。但是我想在c#.net
中编写上面的服务string.format(eg:- string.format("/Student/GetStudentById/{0}/collegeId/{1}",studentId,collegeId)
答案 0 :(得分:4)
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
$http.get(String.format("/Student/GetStudentById?studentId={0}&collegeId={1}", $scope.studentId , $scope.collegeId))
.then(function (result) {
});
答案 1 :(得分:1)
试试这个,
String.format = function(str) {
var args = arguments;
return str.replace(/{[0-9]}/g, (matched) => args[parseInt(matched.replace(/[{}]/g, ''))+1]);
};
string.format("/Student/GetStudentById/{0}/collegeId/{1}",studentId,collegeId)
答案 2 :(得分:0)
你可以使用javascript的sprintf()。
请查看sprintf()
答案 3 :(得分:0)
这是Rest parameter
在ES6中派上用场的地方。而且,这是String.Format
的另一个JS替代方案,就像在C#中一样。
String.prototype.format = function(...args) {
let result = this.toString();
let i = 0;
for (let arg of args) {
let strToReplace = "{" + i++ + "}";
result = result.replace(strToReplace, (arg || ''));
}
return result;
}
E.g。
var path = "/Student/GetStudentById/{0}/collegeId/{1}";
var studentId = "5";
var collegeId = "10";
var result = path.format(studentId, collegeId);
console.log(result);
此输出,
/学生/ GetStudentById / 5 / collegeId / 10