js 让名字显示星号

js 让名字显示星号

function formatName(name) {
    var newStr;
    if (name.length === 2) {
        newStr = name.substr(0, 1) + '*';
    } else if (name.length > 2) {
        var char = '';
        for (var i = 0, len = name.length - 2; i < len; i++) {
            char += '*';
        }
        newStr = name.substr(0, 1) + char + name.substr(-1, 1);
    } else {
        newStr = name;
    }
    return newStr;
}

console.log(formatName('张浩'));    //张*
console.log(formatName('张浩浩'));    //张*浩
console.log(formatName('张浩浩浩浩'));    //张***浩

上一篇:使用jsonp获取腾讯天气


下一篇:紫书UVa1596