12

This is my code

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

In the above code use http service for get student details based on id. but i want to write the above service string.format like in c#.net

(eg:- string.format("/Student/GetStudentById/{0}/collegeId/{1}",studentId,collegeId)
  • 1
    but you can't :) Starting from ECMAScript 6 there is a solution, check here http://stackoverflow.com/questions/3304014/javascript-variable-inside-string-without-concatenation-like-php – Naigel Mar 09 '16 at 06:57
  • Don't forget that in all but the most trivial cases this will be insufficient to compose a URL. You may need to URL escape those substitutions with [`encodeURIComponent`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent). In your particular case a converter from a JavaScript object like `{studentId: $scope.studentId, collegeId: $scope.collegeId}` to a properly encoded series of query parameters is the best plan. – tadman Mar 09 '16 at 07:03
  • 1
    I really dont think string format will actually make any difference in your code except improving code format.So i would suggest you construct the url before making a call to **$http.get(..)** – dreamweiver Mar 09 '16 at 07:04
  • You can use the string replace function like this: '/Student/GetStudentById?studentId={studentId} &collegeId= {collegeId}'.replace('{studentId}',$scope.studentId).replace('{collegeId}', $scope.collegeId) – Koji D'infinte May 13 '18 at 18:33

4 Answers4

6
   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

Try this,

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)
kriznaraj
  • 484
  • 2
  • 11
0

you can use sprintf() of javascript.

please take a look at sprintf()

Sagar Hirapara
  • 1,677
  • 13
  • 24
0

It's where Rest parameter comes in handy in ES6. And, this is yet 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;
}

E.g.

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

This outputs,

/Student/GetStudentById/5/collegeId/10

choz
  • 17,242
  • 4
  • 53
  • 73