在非字母表之前和之后的汉德尔字母表的正则表达式

时间:2014-03-24 14:30:25

标签: javascript regex

伙计我需要正则表达式来替换非字母字符后的字母字符。 例如:

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中的字符是我知道的。

6 个答案:

答案 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;
    }
});

JS Fiddle demo

更新了以上内容以使用对象:

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);

JS Fiddle demo

参考文献:

答案 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);

摆弄示例:http://jsfiddle.net/sYWfM/

答案 5 :(得分:0)

(?!\s+\/)D(?<!\/\s)将使用

之前和之后的空格从/ D /获取D.

(?!\s+{)T(?<!}\s)将从{T}获取带有

之前和之后的空格的T.

(?!\s+)N(?<!\s)将在

之前和之后获取带有空格的N.