function getType(obj) {
let type = typeof obj;
if (type !== "object") { // 先进行typeof判断,如果是基础数据类型,直接返回
return type;
}
// 对于typeof返回结果是object的,再进行如下的判断,正则返回结果
return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1'); // 注意正则中间有个空格
}
console.log(getType({ name: 'wxq' }))
// 把字符串中所有单词的首字母都转换为大写:
var str = 'aaa bbb ccc';
uw = str.replace(/\b\w+\b/g, function (word, index) {
console.log(word)
console.log('uw'+index)
return word.substring(0, 1).toUpperCase() + word.substring(1);
}
);
console.log(uw)
// 说明:匹配一次就执行一次函数,匹配的内容作为参数
//把数字转成对应的汉子
var ary = ["一", "二", "三", "四", "五", "六"]
"123456".replace(/\d/g, function (val,index) {
console.log('ary'+index)
return ary[val - 1]
})
var obj = {
name: 'leaf',
age: 20
}
var str = "我是{{name}},name是我的名字,我今年{{age}}岁";
//最终替换成"我是leaf,name是我的名字,我今年20岁"
function render(template, context) {
template.replace(/\{\{(.*?)\}\}/g, (match, key) => {
console.log(match)
console.log(key)
context[key.trim()]
})
return template.replace(/\{\{(.*?)\}\}/g, (match, key) => context[key.trim()]);
}
console.log(render(str, obj))
console