0

Could someone tell me how could I refactor this method or just give me any idea what should I change? The idea is to create a function to change the name of the authors because I always receive the names on uppercase and I need the only the first letter and exclude (the names are in spanish) "de", "el", "la" and "'","-" that sometimes are used aswell.

  methods: {
    nameAuthor (v) {
      const author = v.toLowerCase().split(' ')
      const exceptions = ["'", '-', 'y', 'de', 'la']
      const longitud = exceptions.length
      for (let i = 0; i < author.length; i++) {
        for (let u = 0; u < longitud; u++) {
          if (!exceptions.includes(author[i])) {
            author[i] = author[i].charAt(0).toUpperCase() + author[i].substring(1)
          }
        }
        if (author[i].includes(exceptions[0])) {
          const especialCharacter = author[i].split("'")
          author[i] = especialCharacter[0] + "'" + especialCharacter[1].charAt(0).toUpperCase() + especialCharacter[1].substring(1)
        }
        if (author[i].includes(exceptions[1])) {
          const especialCharacter = author[i].split('-')
          author[i] = especialCharacter[0] + '-' + especialCharacter[1].charAt(0).toUpperCase() + especialCharacter[1].substring(1)
        }
      }
      return author.join(' ')
    }
  }

Thanks in advance.

MFL
  • 37
  • 4

1 Answers1

1

I would split it into three sub-problems.

  1. Uppercasing the first letter of every "word".
  2. Lowercaseing the special parts of the name

The first problem is answered here and gives you the following function:

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
function capitalizeEachWord(phrase) {
   return phrase.split("'").map(capitalizeFirstLetter).join("'")
                .split("-").map(capitalizeFirstLetter).join("-")
                .split(" ").map(capitalizeFirstLetter).join(" ");

}

The second problem can now be tackled with the following function (assuming that there is always whitespace before and after the special parts of the name):

function lowerCaseSpecialNameParts (name) {
   return name.replace(" De ", " de ")
              .replace(" La ", " la ")
              .replace(" El ", " el ");

}

Now you can combine both of them in your function:

methods: {
    nameAuthor (v) {
      return lowerCaseSpecialNameParts(capitalizeEachWord(v.toLowerCase()));
    }
  }