Using Javascript to extract the initials of names

I am looking for a way to shorten Person and group names

Person :

Robert Smith
David Smith
James Johnson
William

If I use this code snippet:

if(Name.split(",").length === 1)
  return Name.trim().split(" ").map(x => x[0]).reduce((acc, curr) => acc + curr) 
else 
  return ''

The output will be:

  1. RS
  2. DS
  3. JJ

In another scenario, there are sets of names such as:

  1. Robert Smith, David Smith
  2. James Johnson, Robert Smith

In this case, if any comma is found, I would like to return RD in the first case and JS in the second case

Answer №1

It appears that there may be some confusion in your question. From what I understand, you are looking to extract the initials of the first and last name in one scenario, and the initials of each name in another scenario.

Please see the potential solution below:

const scenario1 = "Robert Smith";
const scenario2 = "Robert Smith,David Smith";

function getInitial(data) {

  const chunks = data.split(",");
  
  if ( chunks.length > 1) {
    const initials = [];
    chunks.forEach(chunk => initials.push(chunk[0]));
    return initials.join('');
  } else {
    const [fname, lname] = chunks[0].split(' ');
    return `${fname[0]}${(lname ? lname[0] : '')}`;
  }

}

console.log(getInitial(scenario1))
console.log(getInitial(scenario2))

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 retrieve the value of a specific column in a table upon clicking a

I am working on implementing a functionality in my html table where users can click on a row and see an alert pop up with specific column information. Currently, I have managed to make the alert show the data from the first column of the selected row but I ...

Having trouble retrieving the ID of a button?

I'm attempting to retrieve the ID of a button, but I seem to be getting the ID of the surrounding div instead. This is not the desired outcome. Here's my current approach: HTML <div class="container container-about container-login"> ...

Using JQuery to swap out background images in CSS

I have been working on a slider that is supposed to fade one picture over another. The issue is that the background change seems to only work in the Dreamweaver preview and not in the actual browser. loop = setInterval(function(){ $("#slider").css("ba ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

Using jQuery AJAX for uploading multiple files, each file is sent to the server one at a time using the AJAX method

Here is the HTML code snippet that I am currently working with: <form id="submit-form"> <input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple> <input type="submit"> </form> My goal ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

Is there a way to apply Validators.required just once for all required form fields in a Reactive Form?

Latest version of Angular is 4.4.3. In Reactive Form, you can use Validators.required for each form field as shown below: this.loginForm = this.fb.group({ firstName: ['', [Validators.required, Validators.maxLength(55)]], ...

Is there a way to move a nested object to the outer object?

Is there a way to transfer an object into a nested object contained within the outer object? { criteria: { provider: 2, providerName: 'CLX_gw0', mcc: null, mnc: null, dial_code: null, active: 1 }, page: 1, pageSi ...

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

Lock it up or leave it open - that is the question

My JavaScript/jQuery web application features an object that is accessed for reading and writing by users through DOM events, as well as by the server via web sockets or xhr requests. Although I am aware that JavaScript is single-threaded, I have concerns ...

Refreshing the MarkerCluster following an AJAX request

My current challenge involves an AJAX function that retrieves posts based on users with a specific role. While the query itself works fine, I am encountering an issue with refreshing the markers on Google Maps after the AJAX request is complete and the pos ...

Finding all elements with a specified attribute in jQuery: A comprehensive guide

While looking for an example, I came across one that searches only inputs instead of all elements: https://api.jquery.com/attribute-equals-selector/ Is there a way to modify this example so that it can search all elements in the DOM, and not just inputs ...

What are the limitations of the unhandledrejection event in React when it comes to capturing certain Errors?

unhandledrejection is failing to capture certain errors in a project built using create-react-app. Click here for an example window.addEventListener("unhandledrejection", function(e) { console.log(e); alert(e.reason); }); function handleError() { ...

Changing the color of text in an HTML input field using CSS and JavaScript depending on the input value

Looking for a solution! // Getting user input values var input1 = parseInt(document.getElementById("input1").value); var input2 = parseInt(document.getElementById("input2").value); var input3 = parseFloat(document.getElementById(" ...

Does an event fire after the onclick event completes?

After an onclick event, I need a particular code to be executed. This works well on mobile devices using touchstart and touchend events. However, is there an equivalent event for computers? This is how my current code looks like: document.getElementById( ...

Update the array by verifying if the ID exists and then randomly modify it

I've been experimenting with various methods for some time now, but I've hit a wall where everything I try seems to go wrong. Here's what I attempted: Firstly, I generate a random number and add it to an array: for(.......){ random[i] = ...

Ways to dynamically add a JavaScript file into a webpage

In an attempt to dynamically load a JavaScript file, I utilized a div element with a specific class name to contain the verification script. The script is designed to check if the intended JavaScript file has been loaded and, if not, to generate a new ex ...

Inheritance through Parasitism in JavaScript

Just finished a Douglas Crockford lecture where he introduced the concept of parasitic inheritance in JavaScript. This involves one constructor calling another to modify the object. The code example he provided is: function gizmo(id, secret) { secret = ...

Switching between fixed and unfixed divs causes two absolute divs to alternate

I am currently working on a code to keep a fixed div ("two") in place between two absolute positioned divs ("one" and "footer") while scrolling. However, there is an issue that arises when the browser window is resized. The distance between the footer and ...

Having trouble with updating data in MongoDB using Node.js

I am currently in the process of developing a multiplayer game, complete with a login system. I've encountered some issues when trying to update the user ratings using db.collection.update(). Strangely, whenever I input the username of a player, it re ...