我试图写一个函数,大写字符串中每个单词的第一个字母(将字符串转换为标题情况)。

例如,当输入是“我是一个小茶壶”时,我期望“我是一个小茶壶”是输出。然而,该函数返回“i'm a little tea pot”。

这是我的代码:

函数标题案例(str) { var splitStr = str.toLowerCase().split(“ ”); for (var i = 0; i < splitStr.length; i++) { if (splitStr.length[i] < splitStr.length) { splitStr[i].charAt(0).toUpperCase(); } str = splitStr.join(“ ”); } 返回 str; } console.log(titleCase(“I'm a Little Teapot”));


当前回答

这是你可以用map函数做的,它做的和接受的答案一样,但是没有for循环。因此,可以节省几行代码。

函数titleCase(text) { If (!text)返回文本; If (typeof text !== 'string')抛出"无效参数"; 返回text.toLowerCase()。(' ')。Map (value => { return value.charAt(0).toUpperCase() + value.substring(1); })。加入(' '); } console.log(titleCase(“我是一个小茶壶”));

其他回答

ECMA2017或ES8

const titleCase = (string) => { return string .split(' ') .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length)) .join(' '); }; let result = titleCase('test test test'); console.log(result); Explanation: 1. First, we pass the string "test test test" to our function "titleCase". 2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"] 3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it. 4. In the last, we join the array using space as we split the string by sapce.

或者可以使用replace(),将每个单词的第一个字母替换为“大写”。

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
               return word.replace(word[0], word[0].toUpperCase());
           }).join(' ');
}

titleCase("I'm a little tea pot");

ECMAScript 6版本:

const toTitleCase =(短语)=> { 返回的短语 .toLowerCase () .split (' ') .map(word => word. charat (0).toUpperCase() + word.slice(1)) . join (' '); }; let result = toTitleCase('maRy have a lIttLe LaMb'); console.log(结果);

这里我使用了replace()函数。

function titleCase(str){
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

试试这个函数:

const capitializeName = (name) => {
 
     const splitName = name.split(' ');
        const namesUpper = [];

    for (const n of splitName) {
        namesUpper.push(n[0].toUpperCase() + n.slice(1));
    }
    console.log(namesUpper.join(' '));
};

capitializeName('jahid bhuiyan');