2011年9月2日 星期五

[JavaScript] How to format string?

String.format = function(src){
  if (arguments.length == 0) 
    return null;

  var args = Array.prototype.slice.call(arguments, 1);
  return src.replace(/\{(\d+)\}/g, function(m, i)
  {
    return args[i];
  });
};

Demo:
msg will be "This is variable A and variable B.

var template = "This is variable {0} and variable {1}";
var variable1 = "A";
var variable2 = "B";
var msg = String.format(template, variable1, variable2);

沒有留言:

張貼留言