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

Using jQuery to convert JSON data into an array

My JSON data structure is as follows: { "default": [ [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ] ], "direct": [ [ 13 ...

Unable to modify the default Nuxt favicon

Just getting started with Nuxt and attempting to update the default favicon for my project. I swapped out the favicon.png and favicon.ico files in my static directory, but unfortunately, it didn't take effect. Next, I tried replacing the favicon.png ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

Tips for showcasing an image prior to uploading within a personalized design input file

I am facing an issue with displaying multiple images inside custom style input file labels before uploading them to the database. Currently, the script I am using only displays one image at a time and in random positions. My goal is to have each image ap ...

What is the jQuery method for generating a new element?

Is this the correct way to create an element: $('<div />') or $('<div></div>') Can you confirm if this is the proper syntax for creating an element? Thank you. ...

What is the reason Vue does not execute or update a computed property that contains a reference to 'this' within a filter function?

My question pertains to a select box that is linked to a Vue computed property. I am puzzled by the discrepancy in functionality between two of my computed property attempts. <select> <option v-for="option in filteredItems">{{option.descriptio ...

"Utilizing AJAX to dynamically extract data from PHP and manipulate it in a multi-dimensional

Just starting out with JSON/AJAX and I'm in need of some help... I have a PHP page that seems to be returning [{"id":"1"},{"id":2}] to my javascript. How can I convert this data into something more user-friendly, like a dropdown menu in HTML? Here i ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

Tips for displaying personalized data with MUI DatePicker

I need to create a React TypeScript component that displays a MUI DatePicker. When a new date is selected, I want a custom component (called <Badge>) to appear in the value field. Previously, I was able to achieve this with MUI Select: return ( ...

NodeJS - Headers cannot be modified once they have already been sent to the client

I've recently discovered a solution to the issue I was facing, which involves adding a return statement after sending a response. However, despite implementing the return statement, the error persists. const dbEditCourse = (req, res, db, logger) => ...

Incorporate MUX Player (Video) into Angular versions 14 or 15

Mux offers a video API service with its own player: MUX Player I am interested in integrating this npm package specifically into a component in Angular 14/15. The JavaScript should only be loaded when this particular component is rendered. Integration Th ...

Monitor when users enter commas into input fields in AngularJS

My current challenge involves monitoring user input in a text field and validating the input when a comma is typed, instead of using ng-click="action()". I am looking to implement something like Comma-Typed="action()", but my attempts with ng-change and sc ...

jQuery is implemented prior to the completion of HTML loading

Is there a way to ensure that HTML content loads before executing a JavaScript function? $(document).ready(function() { var x = 10; if(x == 10) { $('h1').text("Its changed !"); alert("Test"); } }) <h1>Hello< ...

Add a new value to the translation token using ng-bind

I'm attempting to loop through an element 5 times using ng-repeat and track by $index. Following that, I aim to utilize the value from $index to supplement a translation token. This appended index value corresponds with the token which retrieves the a ...

Disable the default marker in Mapbox Geocoder

As a newcomer in the world of ReactJS and Mapbox GL JS, I am working on a project where I have successfully integrated a map with Geocoder, Navigation Controls, and Markers based on locations from a JSON file. However, I encountered an issue - whenever I s ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Spin a three-dimensional cube on a platform using three.js with a unique functionality

I am attempting to create an animation featuring a cube on a flat surface. The cube can be rotated along the x/y axis only, with no need to show its underside. I want to be able to tip the cube over any edge - when a side of the cube touches the surface, i ...

Tips for deleting an image file, or any file, from a Node.js Express server

Being a novice in the field of web development, I decided to embark on creating a basic E-commerce application as my first project. I managed to make good progress until I hit a roadblock while trying to remove an image file of a product: I utilized expres ...

What is the best way to ensure a specific section of a website remains visible and fixed at the bottom of the page

I want to set up a simple toolbar with divs and uls containing both anchors and tabs. The position of the toolbar needs to be fixed at the bottom of the page. <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/ ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...