美文网首页
js将字符串中的每一个单词的首字母变为大写其余均为小写

js将字符串中的每一个单词的首字母变为大写其余均为小写

作者: 不会潜水的猫小喵 | 来源:发表于2019-04-24 12:34 被阅读0次
  • 方法一
var str = "You seE whaT you believe!"

function changeStr(str) {
    var arr = str.toLowerCase().split(" ");
    arr.forEach((item, index, array) => {
        arr[index] = item[0].toUpperCase() + item.substring(1, item.length);
    });
    return arr.join(" ");
}

console.log(changeStr(str)); //You See What You Believe!ascript
  • 方法二
var str = "You seE whaT you believe!"

function changeStr(str) {
    var arr = str.toLowerCase().split(" ");
    arr.forEach((item, index, array) => {
        arr[index] = Array.prototype.map.call(item, function(v, i) {
            return i == 0 ? v.toUpperCase() : v;          
        }).join("");
    });
    return arr.join(" ");
}

console.log(changeStr(str)); //You See What You Believe!

相关文章

网友评论

      本文标题:js将字符串中的每一个单词的首字母变为大写其余均为小写

      本文链接:https://www.haomeiwen.com/subject/qsnwgqtx.html