js编写类似c#的一串格式化字符的写法

本文介绍了一种类似于C#的字符串格式化方法,并通过具体示例展示了如何使用该方法来格式化字符串以及在easyui中进行数据列的格式化。

这种方式改变了以前的拼接字符串的方式

 

/*
 * C#样式的字符串格式化
 * Sample
 * strFormat("this is a {0}","test") => "this is a test"
**/
 function strFormat() {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};strFormat() {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};

几种应用方式

1、备注中说的   

strFormat("this is a {0}","test") => "this is a test"

2、easyui的格式化某列数据的时候

{field:'REC_ID',title:'操作',width:150, align: "center", formatter:czformatStr} 

function czformatStr(value,row,index){ 
    return strFormat("<input type='button' value='查看' onclick='openDetail({0})'     class='btn btn-primary radius' style='width: 50px;'/>",JSON.stringify(row));
  
};
function openDetail(row){
	console.log(row.id );
    console.log(row.name );
}

 

 

 

 

C#中如果想要同时替换多个字符串,可以采用多种简便的方式。下面将为你介绍一些常用且高效的解决方案,并给出具体的实现方法。 ### 1. 链接多次`Replace`方法 对于简单的多处替换需求,可以直接连续调用`Replace`方法来完成任务。 #### 示例: 假设我们要把句子中的“cat”、“dog”分别替换成“kitten”和“puppy”。 ```csharp string sentence = "The cat sat on the dog."; sentence = sentence.Replace("cat", "kitten").Replace("dog", "puppy"); Console.WriteLine(sentence); // 输出结果为:"The kitten sat on the puppy." ``` 这种方式简单直接,但如果涉及较多的替换项时显得不够优雅并且效率较低。 --- ### 2. 使用字典映射 + LINQ 或循环遍历 为了提高代码可读性和维护性,特别是当有大量不同关键词需要被替换的情况下,我们可以先准备一个包含原词和目标词汇对照表(如Dictionary),然后通过LINQ查询或者foreach循环依次进行替换。 #### 方案一:基于StringBuilder结合字典与Foreach 这种方法不仅保持了良好的结构化编程风格还能够在一定程度上提升性能(因为减少了不必要的临时对象创建)。 ```csharp var replacements = new Dictionary<string, string> { {"cat", "kitten"}, {"dog", "puppy"} }; var sb = new StringBuilder("The cat and the dog played together."); foreach (var pair in replacements) { int index; while ((index = sb.ToString().IndexOf(pair.Key)) >= 0) sb.Remove(index, pair.Key.Length).Insert(index, pair.Value); } Console.WriteLine(sb.ToString()); // 输出结果为:"The kitten and the puppy played together." ``` > **注意**: 这里我们使用的是`StringBuilder`, 它相较于普通的`String`类型更能有效减少内存分配次数,在处理大规模文本数据时尤为明显。 #### 方案二:利用正则表达式配合匿名函数(适用于固定格式) 如果你希望进一步简化逻辑或面对较为固定的替换规则,则还可以借助于正则表达式的灵活性。 ```csharp using System.Text.RegularExpressions; // 假设所有要替换的关键字都形如${key}, 并存储在一个字典里. var vars = new Dictionary<string, string>() { { "name", "Alice" }, { "age", "25" } }; string template = "Hello ${name}, you're now ${age} years old!"; string result = Regex.Replace(template, @"\$\{(\w+)\}", match => { return vars.TryGetValue(match.Groups[1].Value, out var value) ? value : match.Value; }); Console.WriteLine(result); // 输出结果为:"Hello Alice, you're now 25 years old!" ``` 这种方案特别适合模板渲染等场景下的批量替换操作。 --- 综上所述,针对不同的业务需求可以选择合适的方式来实现多字符串的同时替换。上述每种方法都有其特点及适用范围,请根据实际情况选择最佳实践。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值