Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write string format in angularjs like as c#? [duplicate]

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)
like image 630
durga siva kishore mopuru Avatar asked Mar 09 '16 06:03

durga siva kishore mopuru


People also ask

How do you format a string in JavaScript?

format = function() { var formatted = this; for (var i = 0; i < arguments. length; i++) { var regexp = new RegExp('\\{'+i+'\\}', 'gi'); formatted = formatted. replace(regexp, arguments[i]); } return formatted; };

Is string format the same as printf?

String. format returns a new String, while System. out. printf just displays the newly formatted String to System.

What is printf in JS?

Format in JavaScript. printf is a function that we use in most programming languages like C , PHP , and Java . This standard output function allows you to print a string or a statement on the console.


2 Answers

   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) {
      });
like image 181
durga siva kishore mopuru Avatar answered Oct 16 '22 18:10

durga siva kishore mopuru


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)
like image 21
kriznaraj Avatar answered Oct 16 '22 17:10

kriznaraj