Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de', 'el', 'la', "'", "-") which are common in Spanish.

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

Appreciate your help!

Answer №1

To solve this issue, I propose breaking it down into three separate tasks.

  1. Changing the first letter to uppercase in each "word".
  2. Converting the special parts of the name to lowercase.

The solution for the first task can be found here, providing you with the necessary 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 next step involves handling the special parts of the name with the following function (assuming there is always whitespace before and after these parts):

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

}

You can now integrate both functions into your code like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access attributes of an unknown variable (retrieving 'use')

I encountered an issue (TypeError: Cannot read properties of undefined (reading 'use')) while trying to execute the 'node server.js' command in the Terminal. The error points to my auth.routes.js file. This is the content of my 'a ...

I am encountering the error 'user.matchPassword is not a function' while making a call to my API using bcryptjs in my Node.js and Express application. Can someone help me understand why

const checkUserAuth = asyncHandler( async (req,res)=>{ const { email , password } = req.body; const foundUser = User.findOne({email}); if(foundUser && (await foundUser.verifyPassword(password))){ generate ...

The process of installing Vue CLI on Mac OS triggers numerous warnings and ultimately fails to function properly

I am encountering an issue with installing @vue/cli on my 2017 MacBook Pro running Catalina (10.15.3) with the latest versions of node (v12.18.3) and npm (6.14.6). When I execute the command npm install -g @vue/cli, I receive a series of warnings: npm WARN ...

Converting a PHP variable to JSON in an AJAX call

At the moment, my approach involves using a jQuery Ajax asynchronous function to repeatedly request a PHP page until a large number of spreadsheet rows are processed. I am uncertain if the way I set the variables to be passed to the requested page is corre ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

Send a JSON string directly to Google Cloud Storage without the need for a file upload

When I need to receive data in the form of a JSON string from an external source and then upload it directly to Google Cloud Storage without saving it as a local file first, is there a way to accomplish this task? Thank you. storage .bucket(bucketName) ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...

Ways to accurately determine the size of an array

My issue revolves around an array of objects. When I log the array, everything appears as expected. However, when I use the .length function, it inexplicably returns a value of 0. Check out my code snippet: async fetchTicketType(updatedTicket) { awai ...

Adding a prefix to the imported CSS file

My React app, created with create-react-app, is designed to be integrated as a "widget" within other websites rather than functioning as a standalone application. To achieve this, I provide website owners with minified JS and CSS files that they can inser ...

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

The deployment of the Fire-base Cloud Function was successful and error-free. However, the function does not appear to exist in the Firebase system

After deploying a JavaScript Cloud Function, it shows that the deployment is completed. However, when I check Firebase, the function is not there. Oddly, TypeScript Cloud Functions deploy successfully. I followed all the steps outlined in the original Fir ...

Is there a way to determine in FireBug the specific JavaScript code being received from the server following an Ajax request?

Within my HTML code, I am transmitting a dollar amount to the server in order to convert its currency within the application. Is there a way for me to use FireBug to track and view the JavaScript that is being received from the server following this Ajax ...

Sending information to @select of multiselect in Vue.js - vue-multiselect

I'm currently working on passing a parameter to the @select event function in Vue.js HTML <template> <div class="container"> <div v-for="(billItem, k) in billItems" :key="k" > <div class=&q ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...