Javascript 如何像c#一样在angularjs中编写字符串格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35884922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:20:33  来源:igfitidea点击:

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

javascriptangularjs

提问by durga siva kishore mopuru

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

在上面的代码中,使用 http 服务根据 id 获取学生详细信息。但我想像在 c#.net 中一样编写上述服务 string.format

(eg:- string.format("/Student/GetStudentById/{0}/collegeId/{1}",studentId,collegeId)

采纳答案by durga siva kishore mopuru

   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) {
      });

回答by kriznaraj

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)

回答by vadi taslim

It's where Rest parametercomes in handy in ES6. And, this is yet another JS alternative for String.Formatas in C#.

Rest parameter在 ES6 中派上用场。而且,这是String.FormatC# 中的另一种 JS 替代方案。

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

/Student/GetStudentById/5/collegeId/10

回答by Sagar Hirapara

you can use sprintf() of javascript.

你可以使用javascript的sprintf()。

please take a look at sprintf()

请看一下sprintf()