Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below:

const name = "John Peter Don";
const result = name.match(/\b(\w)/g).join('');
console.log(result)// JPD->> i want only JP

Answer №1

To extract the initials from a string using regex, you can use the match() method to capture all leading capital letters. Once you have these captured letters, you can then combine the first two elements to create the desired output.

var fullName = "John Peter Don";
var nameInitials = fullName.match(/\b[A-Z]/g).slice(0, 2).join("");
console.log(nameInitials);

Answer №2

Following the advice given by Wiktor Stribiżew in the comments

const name = "John Peter Don";
let splitName = name.split(" ");
console.log(splitName[0][0], splitName[1][0]);
console.log("Combined initials: ", splitName[0][0] + splitName[1][0]);

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 in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

Combining the power of jQuery, PHP, JavaScript, and the popular WordPress platform, let's unlock

After going through numerous attempts to find answers for similar issues, I'm unable to get any of the suggested solutions to work. My WordPress site requires a plugin that utilizes jQuery. The main file for my plugin is located at wp-content/plugins ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

Unlock hidden content with a single click using jQuery's click event

I have a question that seems simple, but I can't quite get the syntax right. My issue is with a group of stacked images. When I click on an image, I want it to move to the front and display the correct description above it. Currently, clicking on the ...

Sharing functions between Angular components

Check out my problem statement: https://stackblitz.com/edit/angular-jk8dsj I'm facing two challenges with this assignment: I need to dynamically add elements in the app.component when clicking a button in the key-value.component. I've tried ...

Novice in AngularJS routing

Having trouble with my first AngularJS routing code. The error console isn't much help. Here is my HTML page: <body ng-app="myApp"> <div ng-controller="AppController"> <div class="nav"> <ul> <li> ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

Using javascript to generate fresh dictionaries

Struggling to translate a C# "function" into JavaScript - any advice or tips? Here is the C# snippet: var parameters = new Dictionary<string,string> { { "link", "http://mysite.com" }, { "name", "This is an test" } }; I believe I need to ut ...

Unsynchronized AJAX POST requests fail to function effectively

I am encountering an issue with an AJAX call that I am using to log in a user. Here is the code: function loginUser() { var xmlhttp; if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest() ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

Express encountered an issue when trying to upload a file through AngularJS

I am currently facing an issue with uploading a file to express and subsequently to mongoDB. Despite my efforts, when I attempt to upload the file to express, it appears that no data is being passed through the response. I am utilizing ng-file-upload.min. ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra". Here's my code snippet: var stars = ["Polaris", "Aldebaran", "Deneb", ...

Can you please provide guidance on how to dynamically add number values from an array to a select tag in Vue.js?

I'm trying to populate a select tag with options from an array variable that contains arrays of number values. However, the values being output appear to be blank. Here is the HTML code: <select required id="dropDown"> <option>Sele ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

Generate a collection of div elements as child nodes

I'm working on a project where I have multiple rows with input fields. My goal is to create an array for each row that contains the values of the inputs. For example, if I have 3 rows and the values of 'input1' are 1, 'input2' are ...

Ensure the browser stays anchored at the bottom of the page while employing jQuery to reveal a div

This piece of code allows me to toggle the visibility of a div: <a href="#" class="show_hide">Show/hide</a> <div class="slidingDiv"> My content...... <a href="#" class="show_hide">hide</a></div> <script src="http:// ...