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

新手上路,请多包涵

这是我的代码

$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)

原文由 durga siva kishore mopuru 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 220
2 个回答
   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) {
      });

原文由 durga siva kishore mopuru 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试这个,

 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 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题