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

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

Implement Acrobat JavaScript to enforce a mandatory separate field when a checkbox is selected

As a designer with limited coding skills, I have developed an acrobat form that includes several due date fields. These fields are only mandatory if a specific checkbox is selected. I am looking for the javascript code that will validate the requirement: ...

Hide preloader in AngularJS once repeater has completed execution

Is there a way to hide a preloader div only after all data has finished loading in an ng-repeat loop? Check out this interactive example on Plunker: http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview Here is the HTML code: <div ng-co ...

Running a server-side function on the client-side in Node.js

I am currently working with the following code snippet on the server: var game = io.listen(app); game.sockets.on('connection', function(socket){ storePlayers(socket.id); //Only the player who connects receives this message socket.em ...

I have incorporated jquery-1.2.6.js into my project but I am encountering difficulties utilizing the live method

C# foreach (DataRow Row in oDs.Tables[0].Rows) { LitPreferances.Text += "<Li ID=LI_" + Row["pk_Preference_Branch_ID"].ToString() +"_"+ Row["pk_Preference_BranchType_ID"].ToString() +">" + Row["Branch_Name"].ToString() + "&nbsp;&nbsp;< ...

Generate object connection through dot traversal that is in the form of a string

After reaching out to a downstream source, the response received looks something like this: // for simplicity's sake, let's refer to this variable as resp { "data":{ "abc": { "value":"Hi t ...

Is it possible to modify or delete the question mark in a URL?

Currently, I am working on implementing a search bar for one of my websites hosted on Github. Below is the code I have written for the search bar: <!-- HTML for SEARCH BAR --> <div id="header"> <form id="newsearch" method ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Encountering an issue when trying to use multiple selections in a drop down list with Angular.js

I am facing a major issue. I need to be able to select multiple values from a drop down list, so I implemented bootstrap-multiselect.js. However, I encountered the following error: angularjs.js:107 TypeError: a.forEach is not a function at u.writeValu ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

Providing a callback function along with the specific execution context for it to be executed

myFn is a function that executes an asynchronous task and triggers the callback upon successful completion. SearchController.prototype.show = function (query) { this.searchService.myFn(arg1, this.myCallback); //I want to preserve the reference of `th ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

Is your React application struggling to display large images when bundled with Webpack?

I am facing an issue while trying to display an image from my image folder in a React project using Webpack. I have observed that smaller photos with physically smaller dimensions and file sizes load properly, but larger photos do not render on the screen, ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

Exploring jQuery Ajax: A Guide to Verifying Duplicate Names

When I apply the blur function to a textbox to check for duplicate names using jQuery AJAX, it works perfectly. Here is the code snippet: function checkForDuplicate(data){ $.post("test.php", {name: data}, function (data){ if(data){ ...

Exploring the Depths of Google Chrome: Unleashing the Power of

While a similar question has been posed previously, I am encountering difficulties debugging Javascript in Google Chrome. When I navigate to Page > Developer, the "Debug Javascript" function (Ctrl+Shift+L) is not active. Even trying Alt + ` does not se ...

Server side pagination in AngularJS allows for dynamic loading of data

I am currently facing issues with slow application performance when retrieving large data from the database using Spring MVC and REST. I would like to implement server-side pagination in AngularJS to load only a subset of records. Could anyone provide gu ...

What is the best way to utilize two values in Vue.js 2?

When I attempt to structure my component in the following way: <script> export default { template: '\ <select class="form-control" v-on:change="search">\ <option v-for="option in option ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...