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調(diào)用:
創(chuàng)新互聯(lián)為您提適合企業(yè)的網(wǎng)站設(shè)計(jì)?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強(qiáng)的網(wǎng)絡(luò)競爭力!結(jié)合企業(yè)自身,進(jìn)行網(wǎng)站設(shè)計(jì)及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè), 我們的網(wǎng)頁設(shè)計(jì)師為您提供的解決方案。
var str = "js實(shí)現(xiàn)用{two}自符串替換占位符{two} {three} {one} ".format({one: "I",two: "LOVE",three: "YOU"});
var str2 = "js實(shí)現(xiàn)用{1}自符串替換占位符{1} {2} {0} ".format("I","LOVE","YOU");
2.C#后臺(tái)實(shí)現(xiàn)代碼,下面方法自己寫的;
/// <summary>
/// 字符串格式占位替換
/// </summary>
/// <param name="str">字符串</param>
/// <param name="obj">替換對(duì)象(T,匿名對(duì)象,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#調(diào)用方法:
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);
分享題目:c#和JS字符串format實(shí)現(xiàn)(可實(shí)現(xiàn)JSON對(duì)象,c#實(shí)體對(duì)象,C#匿名對(duì)象,替換)
本文網(wǎng)址:http://www.rwnh.cn/article36/jipgsg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站設(shè)計(jì)、域名注冊、Google、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)