hytzgroup / blog

write & read & though
0 stars 0 forks source link

模板引擎 #22

Open hytzgroup opened 4 years ago

hytzgroup commented 4 years ago
var str = 'Hello,我的名字是<%= name%>';
var dom = document.getElementById('test');
function tmpl(str,data){
    return (str+'')
        .replace(/<%=\s*([^%>]+)\s*%>/g,function(){
            // ["<%= name%>", "name", 11, "Hello,我的名字是<%= name%>"]
            var key = arguments[1];
            return data[key];
        });
}
dom.innerText = tmpl(str,{name:'thomas--->>>'});

/**
    str.replace(regexp|substr, newSubStr|function)
 */
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
console.log(newstr);

var re = /(\w+)\s(\w+)/;
var str = 'YANG THOMAS';
var newstr = str.replace(re,"$2, $1");
console.log(newstr);

var re = /[A-Z]/;
var str = "borderTop";
var newstr = str.replace(re,'-$&');
console.log(newstr);
newstr = str.replace(re,function(matcher){
    return '-'+matcher.toLowerCase();
});
console.log(newstr);

function f2c(x){
    function convert(matcher,p1,offset,str){
        console.log(matcher,p1,offset,str);
        return ((p1-32)*5/9)+"C";
    }
    var test = /(\d+(?:\.\d*)?)F\b/g;
    return (x+'').replace(test,convert);
}
console.log(f2c("212F"));

var str = "x-x_";
var retArr = [];
str.replace(/(x_*)|(-)/g,function(match,p1,p2){
    if(p1){retArr.push({on:true,length:p1.length})}
    if(p2){retArr.push({on:false,length:1})}
});
console.log(retArr);