What is the best way to isolate the text before a particular segment within a string, excluding any blank spaces?

Is it possible to use vanilla JavaScript in order to extract the first string value directly to the left of a specified portion of a longer string, excluding any blank spaces?

Consider the following string: 1 hr 30 min

How could you extract the 1 located to the left of hr, and also how could you obtain the 30 situated to the left of min?

let string = "1 hr 30 min";
if (string.includes("hr")) {
    // code to retrieve the value 1
}
if (string.includes("min")) {
    // code to retrieve the value 30
}

Answer №1

Here is a function that can help you extract hours and minutes from a string then convert them to integers:

const getHoursAndMin = () => {
  const _text = text.replace('min','')
  const [hours, minutes] = _text.split('hr')
  console.log(parseInt(hours), parseInt(minutes))
}

Answer №2

If you follow this method, you will have great control over the outcome.

Ensuring the input string is correct within the function.

"use strict";
function zeroFill(str, width) {
    width -= str.toString().length;
    if (width > 0) {
        return new Array(width + (/\./.test(str) ? 2 : 1)).join('0') + str;
    }
    return str + ""; // always return a string
}
function getHoursOrMin(str, extract, returnType) {
    const _str = str.split(' ');
    let result = "";
    switch (extract) {
        case 'hr':
            const iHr = _str.indexOf('hr');
            result = _str[iHr - 1];
            break;
        case 'min':
            const iMin = _str.indexOf('min');
            result = _str[iMin - 1];
            break;
    }
    switch (returnType) {
        case 'number':
            return Number(result);
        case 'string':
            return result;
        case 'stringZeroFill':
            return zeroFill(result, 2);
    }
}
const str = "1 hr 30 min";
console.log(`${getHoursOrMin(str, 'hr', 'number')}:${getHoursOrMin(str, 'min', 'number')}`);
console.log(`${getHoursOrMin(str, 'hr', 'string')}:${getHoursOrMin(str, 'min', 'string')}`);
console.log(`${getHoursOrMin(str, 'hr', 'stringZeroFill')}:${getHoursOrMin(str, 'min', 'stringZeroFill')}`);
 

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

Remove the bottom border from the active tab by utilizing the <div> and <a> elements

I am facing an issue with a tabbed menu on my webpage. While the menu is functioning correctly, I am struggling to remove the bottom border from the active tab. You can view all of my test code here. While I have come across solutions using <ul> an ...

Implementing a function to save a file to a nested directory in node.js

Currently, I'm utilizing node and express with the following directory structure: public img css js server.js Within server.js, I have the code snippet below for writing to a png file: fs.writeFile('testfile.png', imageData, func ...

What is the total amount within a specified date range when retrieved as JSON?

Consider the following JSON structure: { "timesheets": [ { "user": { "username": "erik", "first_name": "Erik", }, &q ...

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

Surprising pause in the menu transition animation

Currently, I am in the process of developing a menu that seems to have some flaws. One issue is that it appears a bit choppy, but the more concerning problem is the half-second delay after clicking an item before it animates. The concept behind this menu ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

Issue with IntersectionObserver not detecting intersection when the root element is specified

I am encountering an issue with my IntersectionObserver that is observing an img. It works perfectly when the root is set to null (viewport). However, as soon as I change the root element to another img, the observer fails to detect the intersection betwee ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

The functions getFiles and getFolders will consistently retrieve a single file or folder each time they are

When attempting to fetch all files and folders from my Google Drive, the function .getFiles() is only returning one file, while .getFolders() is only returning a single folder. However, I can confirm that there are multiple folders and files in my drive. ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

Unable to retrieve $scope.property using direct access, however it is visible when printed to the console using console.log($

I have successfully populated $scope with data using a get call: httpGetAsync("myUrlWasHere", getBlogPosts, $scope); The console outputs the data when I print console.log($scope): However, when I try to access it using console.log($scope.blogPosts), it ...

the issue of undefined values continue to persist

I've been struggling with this code for a couple of days and it's causing issues. All the other functions are working fine except for this EQUAL function. Here is the code: equal.addEventListener("click", function(e){ if (screen.value == ...

Arrange the select default option using AngularJS as the first option

I've been working on a project using Angular where I fetch data from a JSON file and push it to an array object. This data is then displayed in the options of a select element. My issue is: The default option with selection appears first, but I only ...

Using jqgrid to generate a hyperlink that corresponds to the data's value

I am working with a grid setup similar to the one below: $("#list").jqGrid({ url:'listOpenQueryInXML.php', datatype: 'xml', colNames:['Id','name1', 'name2', 'status', 'type' ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Utilize AngularJS to compile a roster of participants

Just starting out with AngularJS, and although I have some background in JavaScript, AngularJS seems quite challenging to grasp (at least for me). My current issue is as follows... I have a list of players and I want to allow users (such as coaches or an ...

What is the best way to create a JavaScript animation for altering the width of a div element?

Need help with creating a dynamic poll chart based on YES and NO votes? Check out this project where you can visually see the results by clicking HERE. Looking to add some animation effects to your poll? You can achieve a smooth transition using CSS with ...