首字母大写#JS_codewar_4

题目

把字符串参数变成像标题一样,首字母大写。另外,如果给了一些例外的词,这些词如果不是出现在开头,则全部采用小写。

Description:

A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first >letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case >unless >it is the first word, which is always capitalised.

Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The >list of minor words will be given as a string with each word separated by a space. Your function should ignore >the case of the minor words string -- it should behave in the same way even if the case of the minor word >string is changed.

Example

titleCase('a clash of KINGS', 'a an the of') // should return: 'A Clash of Kings'
titleCase('THE WIND IN THE WILLOWS', 'The In') // should return: 'The Wind in the Willows'
titleCase('the quick brown fox') // should return: 'The Quick Brown Fox'

我的答案

function titleCase(title, minorWords) {
    const lower_title = title.toLowerCase().split(' ');

    if (title.length>0) {
        let words = title.toLowerCase().split(' ');
        console.log(words);
        words = words.map(function(x){
            x = x.replace(/./, x[0].toUpperCase());
            return x;
        });
        console.log(words);
        try {
            if (minorWords.length > 0) {
                let minor = minorWords.toLowerCase().split(' ');
                console.log(minor);
                minor.map(function(y){
                    let sq = lower_title.lastIndexOf(y);
                    while (sq>0) {
                        words[sq] = y;
                        sq = words.lastIndexOf(y, sq - 1);
                    }
                });
            }
        }
        finally {
            return words.join(' '); 
        }
    } else {
        return title;
    }
}

别人的答案

function titleCase(title, minorWords) {
  var minorWords = typeof minorWords !== "undefined" ? minorWords.toLowerCase().split(' ') : [];
  return title.toLowerCase().split(' ').map(function(v, i) {
    if(v != "" && ( (minorWords.indexOf(v) === -1) || i == 0)) {
      v = v.split('');
      v[0] = v[0].toUpperCase();
      v = v.join('');
    }
    return v;
  }).join(' ');
}

我的感想

  • 今晚有点乱了,工作事在闹,做js的题也老是卡住
  • 现在已经12点半,不想在动脑了,我准备睡了
  • 我的代码卡了最多的是这个部分:
 words = words.map(function(x){
            x = x.replace(/./, x[0].toUpperCase());
            return x;
        });

试了好久才试出来,一定要words=words... 一定要x=x... 不然就都丢了,去。哎。晚安。

推荐阅读更多精彩内容