将第一个单词的第一个字母和无条件大写数组中的单词大写

时间:2018-02-13 21:49:59

标签: javascript arrays

这是我试过的代码

function sentenceCase(str, unconditionallyCapitalized) {
  let array = str
  str = str.toLowerCase().split(' ')
  console.log(str)
  // str.toUpperCase()
  unconditionallyCapitalized = unconditionallyCapitalized.join().toLowerCase()
  console.log(unconditionallyCapitalized)
  for (var x = 1; x <= array.length; x++) {
    str[0] = str[0].toUpperCase()
    if (str[x].includes('.')) {
      console.log(str[x])

    }
    if (unconditionallyCapitalized.includes(str[x])) {
      str[x] = str[x].split('')
      str[x][0] = str[x][0].toUpperCase()
      str[x] = str[x].join('')
      //console.log(str[x])
    }
  }

  return str.join(' ')
}


let str = 'I watched the storm, so beautiful yet terrific. The face of the moon was in shadow.';
let unconditionallyCapitalized = ['I', 'Moon', 'Shadow'];
console.log(sentenceCase(str, unconditionallyCapitalized));

所以上面的代码给了我Moon而不是Shadow,而且'the'之后的'The'应该大写。

3 个答案:

答案 0 :(得分:1)

尝试下一个代码:

&#13;
&#13;
  function findAndCapitalize(str, arrStr) {
        let tempStr = upperFirstLetter(str);
        arrStr.forEach(item => {
            let index = str.indexOf(item.toLowerCase());
            if(index !== -1) {
                let startPart = tempStr.substring(0, index),
                    endPart = tempStr.substring(index + item.length);
                tempStr = startPart + upperFirstLetter(item) + endPart;
            }
        })
        return tempStr;

        function upperFirstLetter(str) {
            let res = str.charAt(0).toUpperCase() + str.substring(1);
            return res;
        }
    }
    let str = 'I watched the storm, so beautiful yet terrific. The face of the moon was in shadow.';
    let unconditionallyCapitalized = ['I', 'Moon', 'Shadow'];
console.log(findAndCapitalize(str, unconditionallyCapitalized));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为了使这个答案更有帮助: unconditionallyCapitalized.join().toLowerCase()为您提供了一个字符串i,moon,shadow,它不如一系列[&#39; i&#39;,&#39; moon&#39;,&#39; shadow&#39;] (这是我替换它的map函数给你的)

当一个单词有句号时,你只需要控制它。记录它。相反,您可以将单词大写str[x+1](这将是新句子中的第一个单词)。

我用string slicing替换了你的split / toUpperCase / join序列。

最后,您无需转到x <=array.length,只需x<array.length。额外的索引导致错误,因为它无法在该索引处找到任何内容。

&#13;
&#13;
function sentenceCase(str, unconditionallyCapitalized) {

        str = str.toLowerCase().split(' ')
        unconditionallyCapitalized = unconditionallyCapitalized.map(item=>{return item.toLowerCase()})
        str[0] = str[0].toUpperCase()
        for (var x = 1; x < str.length; x++) {
            if (str[x].includes('.') && str[x+1]) {
                str[x+1] = str[x+1].slice(0, 1).toUpperCase() + str[x+1].slice(1)
            } else if (str[x].includes('.')) {
                str[x] = str[x].slice(0, -1)
            }
            if (unconditionallyCapitalized.includes(str[x])) {
                str[x] = str[x].slice(0, 1).toUpperCase() + str[x].slice(1)
            }
        }

        return str.join(' ') + '.'
    }


    var str = 'I watched the storm, so beautiful yet terrific. the face of the moon was in shadow.';
    var unconditionallyCapitalized = ['I', 'Moon', 'Shadow'];


var answer =  sentenceCase(str, unconditionallyCapitalized)
console.log(answer)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是一种现代的方法。这里的关键是在数组上使用.find()来检查你想要大写的单词列表(数组)中的单词是否与你正在迭代的当前单词相匹配(在通过空格将字符串分解为数组之后)。

.replace(/\W/g, '')会删除您单词中的所有非单词字符,这样shadow.就可以匹配Shadow(当然是在较低的情况下)。

const cleanString = str => str.replace(/\W/g, '').toLowerCase();
const capitalizeCertainWords = (str, words) =>
    str
        .split(' ')
        .map(
            word =>
                words.find(
                    capitalizedWord =>
                        cleanString(word) === cleanString(capitalizedWord)
                )
                    ? word.substring(0, 1).toUpperCase() + word.substring(1)
                    : word
        )
        .join(' ');

const str =
    'I watched the storm, so beautiful yet terrific. The face of the moon was in shadow.';
const unconditionallyCapitalized = ['I', 'Moon', 'Shadow'];

console.log(
    capitalizeCertainWords(str, unconditionallyCapitalized)
);