开发者

How can I replace .NET string-placeholders with actual values in javascript?

I have a string (coming from ASP.NET) which contains one or more placeholders. In .NET I'm using the string.Format() method to replace the placeholders with actual values:

var str = "aaa {0} bbb {1} ccc {2:0.0}";
var result = string.Format(str, new [] {1, 2, 33.123});

Now I have to do the same in javascript, but I'm struggling with the regular expression. The following function works fine for the simple placeholders like "{0}" but fails for more complex ones like "{3:0.0}":

function FormatString(txt, args) {
  for (i = 0; i < args.length; i++) {
    txt = txt.replace('{' + i + '}', args[i开发者_如何学C]);
  }
  return txt;
}

//e.g:
FormatString("aa {0} bb {1} cc", [1, 2]);
// returns "aa 1 bb 2 cc"

For the complex placeholders, I tried to modify my function to use regular expressions, but so far I failed to come up with a working RegExp. This is what I tried:

function FormatString2(txt, args) {
  for (i = 0; i < args.length; i++) {
    txt = txt.replace(new RegExp('{' + i + '.*}'), args[i]);
  }
  return txt;
}

// does not work correctly, i.e:
FormatString2("aa {0:0.0} bb {1} cc", [1, 2]);
// returns "aa 1 cc" instead of "aa 1 bb 2 cc"

Any hints how to properly replace these .NET-placeholders in javascript (using RegExp or not)?


Ok after some more googling I guess I found a solution which seems to work:

function FormatString2(txt, args) {
  for (i = 0; i < args.length; i++) {
    txt = txt.replace(new RegExp('{' + i + '[^}]*}'), args[i]);
  }
  return txt;
}


There are many implementations of sprintf in JavaScript -- but if you prefer this syntax, then you'll want something like this (untested):

// Define unchanging values outside of any function call:
var formatter = /{(\d+)([^}]*)}/g;
// If the colon is the flagging character, then you'll want:
// /{(\d+):?([^}]*)}/g
var modes = function(mode) {
  switch (mode) {
    case "0.0": 
      return function(str) { /* do something with the string here */ };
    // Additional cases go here.
    default:
      return function(str) { return str; };
  }
};
function replacer(key, mode) {
  return modes(mode)(args[key])
}

function FormatString(txt, args) {
  var l = args.length, i = 1;
  while (i < l) {
    txt = txt.replace(formatter, replacer);
  }
  return txt;
}

You could also use an object literal rather than a function and do your flag checking in replacer to translate between flags like 0.0 and a key (like decimal-number). It all depends on how robust a solution you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜