您好,登錄后才能下訂單哦!
String.prototype.format= function () {
if (arguments.length == 0) return this;
var param = arguments[0];
var s = this;
if (typeof (param) == 'object') {
for (var key in param)
s = s.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
return s;
} else {
for (var i = 0; i < arguments.length; i++)
s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
return s;
}
}
javascript調用:
var str = "js實現用{two}自符串替換占位符{two} {three} {one} ".format({one: "I",two: "LOVE",three: "YOU"});
var str2 = "js實現用{1}自符串替換占位符{1} {2} {0} ".format("I","LOVE","YOU");
2.C#后臺實現代碼,下面方法自己寫的;
/// <summary>
/// 字符串格式占位替換
/// </summary>
/// <param name="str">字符串</param>
/// <param name="obj">替換對象(T,匿名對象,Newtonsoft.Json.Linq.JObject)</param>
/// <returns></returns>
public static string Format(string str, object obj)
{
if (str.Length == 0)
{
return str;
}
string s = str;
if (obj.GetType().Name == "JObject")
{
foreach (var item in (Newtonsoft.Json.Linq.JObject)obj)
{
var k = item.Key.ToString();
var v = item.Value.ToString();
s = Regex.Replace(s, "\\{" + k + "\\}", v, RegexOptions.IgnoreCase);
}
}
else
{
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
{
var xx = p.Name;
var yy = p.GetValue(obj).ToString();
s = Regex.Replace(s, "\\{" + xx + "\\}", yy, RegexOptions.IgnoreCase);
}
}
return s;
}
c#調用方法:
string ssew = "{one:'I',two: 'LOVE',three: 'YOU'}";
Newtonsoft.Json.Linq.JObject o2 = Newtonsoft.Json.Linq.JObject.Parse(ssew);
string sew = CommonFunc.Format("{ONE} {TWO} {three} ", o2);
var ste = new { one = "I", two = "LOVE", three = "You" };
string ese = CommonFunc.Format("{ONE} {TWO} {three} ", ste);
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。