Split the string in JavaScript and then count the characters to decrypt

I am currently working on a task that involves splitting a string at every space. I have successfully achieved this using .split(" "), but now I need to determine the length of each individual string. My goal is to check if a given string includes a middle initial or not. For example, when the name "John M Smith" is entered, I can identify the separate words. However, in cases where a middle initial is not provided, the last name will be mistakenly categorized as the middle initial. How should I approach solving this issue? Any advice would be greatly appreciated.

Answer №1

To determine the number of names in a string, use the length property of the array storing the separated strings:

var separateStrings = stringVar.split(' ');
var numOfNames = separateStrings.length;

For instance, consider the following example code snippet:

var i = document.getElementById('names'); // assuming an input element with id="names"

i.onkeydown = function(e){
    if (e.keyCode == 13){
        var stringVar = this.value,
            separatedNames = stringVar.split(' '),
            numOfNames = separatedNames.length;

        alert(numOfNames);
    }

};​

Check out the live demo on JS Fiddle here.

Answer №2

To determine if a middle name exists, you can check the length of the result array:

var fullName = "John Smith".split(" ");
if(fullName.length == 2) {
  //There is no middle name
  //fullName[0] is "John"
  //fullName[1] is "Smith"
}
else if(fullName.length == 3) {
  //Middle name is present
}

Answer №3

Here is a useful code snippet:

let name = "Jane A Doe".split(" ");
let first = name[0],
    middle = (name[2] && name[1]) || "",
    last = name[2] || name[1];

This piece of code will accurately assign values to each variable, accounting for cases where there is a middle initial and where there isn't. Keep in mind that this assumes there will always be a first and last name, with the middle initial being optional.

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

Displaying the Status of a Script that is Running Asynchronously

My script takes around 5 minutes to complete and sends an email with a file attachment once finished. The entire process happens on a single PHP page without using AJAX. I want the front end to handle form submission seamlessly, processing the request in ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

Sending forms through the .NET platform

On my .NET page, I have implemented client-side validation for a submit button within the form element. var register = $('#<%= Register.ClientId %>'); register.click(function(){ validation.init(); return false; }); Disabling the f ...

Kohana ajax causing removal of JQuery Data attributes

Currently, I am developing an application where jquery data is used to pass variables to HTML elements. It has been successful in one part of the site when the data attributes are added to a tr tag. The following code works: <tr class="js-instructions ...

What is the solution to determining the width in AngularJS without taking the scrollbar size into account

How can I retrieve the window inner height without including the scrollbar size when using $window.innerHeight? ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

Searching in the Kendo Dropdown List using text and value

$(document).ready(function() { $("#selection").kendoDropDownList({ filter: "startswith", dataTextField: "SelectionName", dataValueField: "SelectionID", dataSour ...

Running the Express service and Angular 6 app concurrently

Currently, I am in the process of developing a CRUD application using Angular6 with MSSQL. I have managed to retrieve data from my local database and set up the necessary routes, but I am encountering difficulties when it comes to displaying the data on th ...

Can you tell me the title of this pointer?

When utilizing the drag function in the RC-tree, a specific cursor is displayed. I am interested in using this cursor in another dragzone on my website, but I am uncertain of its name. This same cursor also appears when dragging highlighted text into the b ...

Updating a marker's latitude and longitude using Laravel, Google API, and Ajax: A step-by-step guide

I'm struggling with sending the marker coordinates to a controller using ajax. I have named my routes 'update-marker-position' and included csrf_token(), but I am still seeing an error message in the logs. In my web.php file: Route::post(&a ...

Why isn't my Bootstrap dropdown displaying any options?

I am new to web development and attempting to create a button that triggers a dropdown menu when clicked. I have tried the following code, but for some reason, the dropdown is not working correctly. Can anyone help me identify the issue or correct my code? ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

What is the best way to showcase a table below a form containing multiple inputs using JavaScript?

Context: The form I have contains various input fields. Upon pressing the [verify] button, only the "first name" is displayed. My goal is to display all input fields, whether empty or filled, in a table format similar to that of the form. Exploration: ...

What is the best way to implement an event listener for every button in a table row outcome?

I have a Rails application where I am populating a table using an @results variable, with each row representing a @result. My goal is to have buttons associated with each @result, and I'm attempting to use a JavaScript event listener for each button a ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

Collaborate by sharing local storage with other systems

One of my systems (x.x.x.x: 8000) creates a localstorage after logging in. Now, when a user interacts with another system (x.x.x.x: 8001) by clicking a specific button, the information stored in the initial system's localstorage (x.x.x.x: 8000) is nee ...

How can I add an object to an array of objects in Vue.js?

Hey there! I'm new to Vue and currently working on understanding the whole concept of Vue and how to use it. Right now, my focus is on learning lists. JS: Vue.config.productionTip = false; new Vue({ el: '#app', data: { items: [ ...

Sending data using the AJAX method with integers

Utilizing AJAX to send a high score to a SQLite database's highScores table, the total of the high score must be calculated through a query and then retrieved back from the database. How can I ensure that the score is sent as an integer through AJAX t ...

Utilize a variable within the res.writeHeads() method in Node.js

Greetings all. I have encountered an issue that I need help with: Currently, I am using this block of code: res.writeHead(200, { "Content-Length": template["stylecss"].length, "Connection": "Close", "X-XSS-Protection": "1; mode=block", "S ...