伙计我需要正则表达式来替换非字母字符后的字母字符。 例如:
var Name = "joe";
var Time = "10:30";
var Date = "24-03-2014";
var before = "hey N how are you? iam waiting you at {T} on /D/";
var after = before.replace("N", Name);
after = after.replace("T", Time);
after = after.replace("D", Date);
// -->Output = hey joe how are you? iam waiting you at {10:30} on /24-03-2014/";
知道formatString中的字符是我知道的。
答案 0 :(得分:2)
我建议:
var after = before.replace(/\b[NTD]\b/g, function(a){
switch (a){
case 'N':
return Name;
break;
case 'D':
return Date;
break;
case 'T':
return Time;
break;
}
});
更新了以上内容以使用对象:
var details = {
'N' : "joe",
'T' : "10:30",
'D' : "24-03-2014"
},
before = "hey N how are you? iam waiting you at {T} on /D/";
var after = before.replace(/\b[NTD]\b/g, function(a){
return details[a] || a;
});
alert(after);
参考文献:
答案 1 :(得分:1)
您可以执行以下替换:
查找内容:\bN\b
替换为:Name
变量的值
查找内容:{T}
替换为:{[VALUE_OF_Time_VARIABLE]}
查找内容:/D/
替换为:/[VALUE_OF_Date_VARIABLE]/
您可能还会考虑自动template solution。
答案 2 :(得分:1)
您可以使用:
after = before.replace(/\bN\b/, Name).replace(/\bT\b/, Time).replace(/\bD\b/, Date);
答案 3 :(得分:0)
您可以使用new RegExp(pattern, flags)
从 String 构建 RegExp ,这样您就可以编写这样的函数
function swap(haystack, needle, replacement) {
needle = new RegExp('\\b' + needle + '\\b', 'g');
return haystack.replace(needle, replacement);
}
swap(
'Meet me at {T}',
'T',
'18:30'
); // "Meet me at {18:30}"
答案 4 :(得分:0)
您可以使用模板引擎。一个很好的例子是Mustache.js(https://github.com/janl/mustache.js)
检查此代码:
var view = {
user: "Joe",
time: "20:00",
date: "01/01/2014"
}
var template = "hey {{user}} how are you? iam waiting you at {{time}} on {{date}}";
var output = Mustache.render(template, view);
答案 5 :(得分:0)
(?!\s+\/)D(?<!\/\s)
将使用
(?!\s+{)T(?<!}\s)
将从{T}获取带有
(?!\s+)N(?<!\s)
将在