How to write string format in angularjs like C #?

This is my code.

$http.get("/Student/GetStudentById?studentId=" + $scope.studentId + "&collegeId=" + $scope.collegeId) .then(function (result) { }); 

In the code above, use the http service to retrieve student information based on ID. but I want to write the above line service.format, as in C # .net

 (eg:- string.format("/Student/GetStudentById/{0}/collegeId/{1}",studentId,collegeId) 
+7
javascript angularjs
source share
4 answers
  String.format = function () { // The string containing the format items (eg "{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) { }); 
+3
source share

Try it,

 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) 
+1
source share

you can use sprintf () javascript.

look at sprintf ()

0
source share

Here, where the Rest parameter comes in handy in ES6. And this is another JS alternative for String.Format , as in 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; } 

eg.

 var path = "/Student/GetStudentById/{0}/collegeId/{1}"; var studentId = "5"; var collegeId = "10"; var result = path.format(studentId, collegeId); console.log(result); 

This conclusion,

/ student / GetStudentById / 5 / collegeId / 10

0
source share

All Articles