Implementing string normalization in JavaScript

I need to create a JSON object by parsing a search string.

Examples of input strings

"American01 SFO2016"
"American 01 SFO 2016"
"American-01 2016SFO"
"American:01 SFO16"

The expected output for all these strings is

{
airline: "American",
flightNo: 01,
airport: "SFO",
year: "2016"
}

Code snippet

var str = "American-01 2016SFO";
document.write(str.split(/[ :-]+/));

This code will output American,01, 2016SFO

I have two questions: 1) How can I split 2016SFO into 2016 and SFO? 2) Is this the best approach for achieving this?

Here's a demo link https://jsfiddle.net/pdubey84/msebk5a2/

Answer №1

Check out the code snippet below for a functioning example:

getNormalizedData('American01 2016 SFO');
getNormalizedData('Amercian 01 SFO 2016');
getNormalizedData('American-01 SFO2016');
getNormalizedData('Amercian:01 SF0-2016');

function getNormalizedData(str) {
  var airline = str;
  var flightNo = "";
  var airport = "";
  var year = "";
  var airlineEndMatch = str.match(/[ \d\-\:]/);
  if (airlineEndMatch) {
    airline = str.substr(0, airlineEndMatch.index);
    str = str.substr(airlineEndMatch.index);
    if (!str[0].match(/\d/))
      str = str.substr(1);

    var flighNoEnd = str.indexOf(" ");
    flightNo = str.substr(0, flighNoEnd);
    str = str.substr(flighNoEnd);
    airport = str;
    var yearMatch = str.match(/\d{4}/);
    if (yearMatch) {
      year = yearMatch[0]
    airport = (airport.replace(year, ""))
        .trim()
        .replace("-", "");
    }
   }

var flight = {
  airline: airline,
  flightNo: flightNo,
  airport: airport,
  year: year,
}

console.log(flight);
}

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

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...

What sets apart "React.useState setter" from "this.setState" when updating state?

After clicking on the button in AppFunctional, the component fails to update even though the state has changed. However, everything works fine in AppClass. In both cases, we are mutating the original state with "push", but I'm struggling to understan ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

Discovering absent data in JSON with the help of Python

I'm encountering an issue where I need to categorize a dataset into completed and incomplete sections. To achieve this, I aim to insert flags like 'complete' in the JSON data structure, as shown in the example below. Here is the dataset tha ...

Enhance the functionality of the Bootstrap navbar by enabling the slideUp and slideDown effects

I can't get jQuery's slideUp and slideDown methods to smoothly animate the Bootstrap navbar. When I tried using the slideUp method, the navbar only slid up a little before disappearing completely, and the same issue occurred with the slideDown me ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

JS Implementation of the Coin Change Algorithm

I've been grappling with this algorithm for the past few days, but unfortunately I haven't been able to come up with a successful solution yet. The available solutions seem to be too advanced for my current level of understanding. This problem mu ...

Getting started with JavaScript arguments can be overwhelming for newcomers

Can you figure out why the variable 'a' doesn't increase by 1 in the following code snippet? var a = 5; function abc(y) { y++; } abc(a); // The value of 'a' remains 5, instead of increasing to 6. Why is that? However, when ...

What is the best way to generate a hyperlink that will open a raphael graph in my own browser?

If I have a web page that includes a raphael.js drawing in <div id='my-canvas'></div> <body> <div id='part_one'>...</div> <div id='my-canvas'></div> <div id='part_thre ...

What's the best way to add row numbers within ajax requests?

I wrote a function that retrieves values from a form using jQuery's AJAX method: function getvalues(){ var sendid = $('#id').val(); $.ajax({ type: "POST", url: "ready.php", data: {sendid} }).done(function( result ) { $("#msg").html( "worked ...

Creating a personalized router with Nuxt

Currently, I am working on setting up a custom route in Nuxt using the following nuxt.config.js: router: { base: '/', router: { extendRoutes (routes, resolve) { routes.push({ name: 'custom', pa ...

Load images and audio files using jQuery AJAX prior to the page being rendered

Recently, I embarked on a new project - a web app that incorporates numerous images and mp3 sounds. However, I encountered an issue where new images and sounds would load over time as users explored different parts of the app. To address this problem, I de ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

Tips for preserving component state during page rerenders or changes

I created a counter with context API in React, and I'm looking for a way to persist the state even when the page is changed. Is there a method to store the Counter value during page transitions, similar to session storage? My app utilizes React Router ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

JavaScript's Date() function accurately displays the timezone, but it inconsistently displays the

I have encountered an unusual behavior while attempting to retrieve the current date using Date() in JavaScript. Initially, I changed the timezone to Cuba with the command: sudo ln -sf /usr/share/zoneinfo/Cuba /etc/localtime Subsequently, I executed Date ...

GATSBY: Error: Unable to find the specified property 'includes' within an undefined value

I'm struggling to figure out how to properly filter images in my portfolio website as discussed in this post… Every time I attempt it, I encounter the following error: "TypeError: Cannot read property 'includes' of undefined" D ...

Attempt to generate a function in JavaScript that mirrors an existing one

How can I create a javascript function similar to loadAllOriginal, but with the value of the variable allEmployees being a list of employee objects (ID, FirstName, LastName)? I am attempting to implement this method in combination with autocomplete from ...