簡體   English   中英

如何在JavaScript中將.NET字符串占位符替換為實際值?

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

我有一個字符串(來自ASP.NET),其中包含一個或多個占位符。 在.NET中,我使用string.Format()方法將占位符替換為實際值:

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

現在,我必須在javascript中做同樣的事情,但是我在正則表達式方面苦苦掙扎。 以下函數對於簡單的占位符(如“ {0}”)有效,但對更復雜的占位符(如“ {3:0.0}”)無效:

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

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

對於復雜的占位符,我試圖修改我的函數以使用正則表達式,但是到目前為止,我還沒有想到可以正常工作的RegExp。 這是我嘗試的:

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"

任何提示如何正確替換javascript中的這些.NET占位符(是否使用RegExp)?

好吧,經過更多的谷歌搜索之后,我想我找到了一個似乎可行的解決方案:

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

JavaScript中有很多 sprintf的實現-但是,如果您喜歡這種語法,那么您將需要這樣的內容(未經測試):

// 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;
}

您也可以使用對象文字而不是函數,並在replacer進行標志檢查以在標志(例如0.0和鍵(例如decimal-number )之間進行轉換。 這完全取決於您需要的解決方案的穩定性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM