Strip excess white space from a complex string using Javascript

I have the following sets of strings:

14/04/22 10:45:20 12.08N 87.65W 15.0 2.9ML Frente a Corinto
14/04/21 11:05:34 12.10N 87.70W 140.0 3.5MC Cerca de Masachapa
14/04/22 09:00:09  12.35N  86.44W  12.4  1.3ML Cerca del volcan Momotombo
14/04/21 23:33:37  12.35N  86.63W   7.1  1.0ML SO de La Paz Centro/Nagarote

Now, I am seeking help to transform them into this format:

14/04/22-10:45:20-12.08N-87.65W-15.0-2.9ML-Frente a Corinto
14/04/21-11:05:34-12.10N-87.70W-140.0-3.5MC-Cerca de Masachapa
14/04/22-09:00:09-12.35N-86.44W-12.4-1.3ML-Cerca del volcan Momotombo
14/04/21-23:33:37-12.35N-86.63W-7.1-1.0ML-SO de La Paz Centro/Nagarote

If anyone can assist me in achieving this using Regular Expressions in JavaScript, it would be greatly appreciated.

Thank you!

PS. Edited for clarification. Specifically, I aim to replace all spaces with "-", excluding those spaces before a letter, and also replacing the space before the first occurrence of a letter at the beginning of each word. Please refer to my example above for better understanding of my requirements.

Answer №1

To implement lookahead regex, you can follow this example:

var str = '14/04/21 23:33:37  12.35N  86.63W   7.1  1.0ML SO de La Paz Centro/Nagarote';

var result = str.replace(/ +(?![A-Za-z])/g, '-').replace(/ (?=[a-zA-Z])/, '-');
//=> 14/04/21-23:33:37-12.35N-86.63W-7.1-1.0ML-SO de La Paz Centro/Nagarote

Answer №2

Is this what you're looking for? Pretty straightforward. This code snippet will replace the first space followed by a number with a hyphen in the given string:

"22/10/21 08:30:12 15.45S 120.67E 8.0 3.5ML Near Broome".replace(/\s(?=\d)/, '-').replace(/ /, '-')
"22/10/21-08:30:12-15.45S-120.67E-8.0-3.5ML-Near Broome"

Answer №3

If you're finding that regex alone isn't giving you the results you need, this code could be just what you're looking for. We use regex to identify any string that contains numbers, as they are the constant in the data. We then store all the data in a temporary array and generate the desired output once it's complete.

function formatString(str) {
    var ss = str.split(' ');
    var listItems = [];
    var listStrings = [];
    var finalStringInt = "";
    var finalStringStr = "";

    for (var t = 0; t < ss.length; t ++) {
        var matchNumer = ss[t].match(/\d+/g);
        if(matchNumer != null){
            listItems.push(ss[t]);
        } else {
            listStrings.push(ss[t]);
        }

    }
    for (var sx = 0; sx < listItems.length; sx++) {
        finalStringInt += listItems[sx]+"-";
    }

    for (var xx = 0; xx < listStrings.length; xx++) {
        finalStringStr += listStrings[xx]+" ";
    }

    return finalStringInt.trim() + finalStringStr.trim(); 
}

var s="14/04/21 23:33:37  12.35N  86.63W   7.1  1.0ML SO de La Paz Centro/Nagarote";
console.log(formatString(s));

Desired Output:

14/04/22-10:45:20-12.08N-87.65W-15.0-2.9ML-Frente a Corinto
14/04/22-09:00:09-12.35N-86.44W-12.4-1.3ML-Cerca del volcan Momotombo 

Answer №4

Avoid using regular expressions completely:

let data = "14/04/22 10:45:20 12.08N 87.65W 15.0 2.9ML Frente a Corinto";
data = data.split(' ', 6).join('-');
console.log(data);

result:

14/04/22-10:45:20-12.08N-87.65W-15.0-2.9ML

This code snippet will substitute the first six spaces in the input string.

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

Get tabular information in xlsx format by utilizing the xlsx npm package for download

I have been attempting to convert my json-like data into an xlsx file format. I utilized the xlsx npm package and followed various code samples available online, however, when trying to open the file in Excel, I encountered the following error: https://i.s ...

What is the best way to pass a value to a modal and access it within the modal's component in Angular 8?

How can I trigger the quickViewModal to open and send an ID to be read in the modal component? Seeking assistance from anyone who can help. Below is the HTML code where the modal is being called: <div class="icon swipe-to-top" data-toggle="modal" da ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

MUI Error: Incorrect prop provided to menu item

I am encountering an issue with a React component that generates a list of elements, each containing a button to open a menu. The problem is that the props being passed to each menu are incorrect; they always reflect the props of the last element in the ...

Guide on implementing hover effects in React components

Within my component SecondTest, I have defined an object called useStyle which sets the background color to red. Is it feasible to add a hover effect to this object? const useStyle = { backgroundColor: "red", }; function SecondTest() { return < ...

Rgd: Double-Sided Horizontal Slide Control

While browsing the internet, I came across several examples of horizontal sliders with adjustable values. For example, if I set the maximum value as 100 and move the slider 10 sectors to the left, each sector would decrease by 10. What I am trying to ach ...

JavaScript makes Chrome Hard Reload a breeze

We've created a browser-based app using AngularJS and are currently testing it with a group of clients. One major challenge we're facing is explaining how to "Empty Cache and Hard Reload" using the Chrome browser (by pressing F12, then clicking o ...

Creating a dynamic form that efficiently captures user information and automatically redirects to the appropriate web page

Sorry for the unusual question, but it was the best way I could think of asking. I have come across websites with fill-in-the-blank lines where you can input your desired information and then get redirected to another page. For example: "What are you sea ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

Clicking through the button inside Vuetify's text-field append slot

While working on creating Vuetify's v-text-field with a slot named append containing a button, everything seems to be functioning correctly except for the fact that when I click the button, it goes through and focuses on the text field. On mobile devi ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

Guide on determining the total count based on a specific condition with the help of jQuery

Using AJAX, I have successfully retrieved all status values such as Active, ACTIVE_DRAFT, and Pending. However, I only want to select the statuses that are equal to ACTIVE. To do this, I am using an if condition which is working fine. After filtering by st ...

Using regular expressions, eliminate the element from a JSON object that contains a specified property

Imagine I have a string representing a JSON object. It could be invalid, with some params that will be replaced by another system (e.g. %param%). The task at hand is to remove all objects with a known propertyName equal to "true" using regex. { "someT ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

Forward the jsp to the servlet before navigating to the following page

Issue: After submitting the JSP form on Page1, it redirects to a server-side JSP page but appears as a blank page in the browser. Instead, I want it to redirect to Page2 which includes a list box that highlights the newly created item. Seeking help with t ...

Determining the scroll position of a JQuery Mobile collapsible set upon expansion

I am utilizing jQueryMobile (v1.4.0) collapsible set / accordions to showcase a list of elements along with their content, which can be seen in this jsFiddle. <div id="List" data-role="collapsible-set"> <div data-role="collapsible" data-conte ...

Have you ever wondered why req.body returns as undefined when using body parser?

Every time I attempt to make a post request, I keep receiving an error message stating that req.body is returning as undefined. Below is the content of my server.js file: import express from 'express'; import bodyParser from 'body-parser&ap ...

Convert several XML nodes to display in an HTML format

I am currently facing an issue where I am trying to display all the nodes of a specific tag in XML. Although it does filter the data correctly, only one node is showing up. Is there anyone who can assist me with this problem? Below is the XML content: < ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...