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

All menus effortlessly sliding out simultaneously

I'm having an issue with my navigation bar. I want each link to slide its corresponding DIV up or down when clicked. However, all the DIVs are sliding and when clicking on the same link everything slides up. How can I fix this problem? This is my HT ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

Only show the directive methods when using "ng-if"

I am facing an issue with the Opentoke Library directive, particularly when I use the ng-if. The reason for implementing the ng-if is that WebRTC is not supported on IOS devices, so it displays an alert after the DOM has loaded. <div class="opentok" ng ...

Exploring deeply nested objects within Express by iterating through them

I am trying to figure out how to iterate through objects in Express.js. I can retrieve information from the JSON file, but when I attempt to loop through it, I keep getting an error saying that it's not defined. What could I be missing here? My goal ...

What is the process for updating the combination selector for each product within a specific category in PrestaShop 1.7?

We have a range of products in a specific category, each offering multiple pack sizes with varying prices (e.g. 1, 3, 5, 10, 25, 50, 100). EDIT: The homepage features these products displayed using an owl-carousel within a div element: When a customer se ...

Utilizing a function that changes a UNIX timestamp to a month/day/year layout

I have been working with ExpressJS and am facing a challenge in converting the UNIX format date to mm/dd/yyyy format when retrieving the date value. I attempted to create a function for this conversion, but encountered an issue where my methods cannot be c ...

Loading a Component in React (Next.JS) Once the Page is Fully Loaded

After implementing the react-owl-carousel package, I encountered an error upon refreshing the page stating that "window is not defined." This issue arises because the module attempts to access the window object before the page has fully loaded. I attempted ...

Unlimited scrolling: Fetching additional data via an Ajax request?

I am working on setting up a table with infinite scroll functionality to showcase user information such as name, address, and email. To accomplish this, I began by importing the json-server package and creating an API endpoint using fakerjs in a separate f ...

Preserve JSON information using Ajax

Here is the current code snippet I am working with: Play.save = function() { //Hide the buttons this.printButton.visible = false; this.saveButton.visible = false; this.backButton.visible = false; //Force the game to re-render. th ...

Data assigned to KendoUI chart must have keys that do not consist of numbers

When I input the following simple data into a KendoUI chart, the chart displays the data correctly. var data = [ {"state":"NY","abc":12312}, {"state":"AZ","abc":12312}, {"state":"CA","abc":12312}, ...

What steps should be followed to display an HTML page within an HTML div?

The question I have is a bit misleading, as I'm not looking for guidance on how to open an HTML document in a div. Rather, I am currently facing an issue where I am unable to replace the HTML file that I have already placed in a div. Initially, I pla ...

Guide to utilizing the Array find method to retrieve an object in JavaScript

I'm currently working on a Homework assignment that involves passing a parameter called userID to an arrow function. Within this function, the task is to use the .find method on an array named users. This find function should retrieve an object contai ...

In search of a screenplay that mirrors a specific scenario

I recently came across this website: One interesting feature is that all the content loads dynamically on the same page. Instead of loading separate pages, it pauses to fetch the content before smoothly scrolling to the correct section. ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

What are the steps to develop a progress bar using PHP and JavaScript?

In the application I'm developing, PHP and JavaScript are being used extensively. One of my tasks involves deleting entries from the database, which is a time-consuming process. To keep the end-user informed, I would like to provide updates on the pr ...

Working with Node.js and MySQL can involve using callbacks within nested queries

I am trying to add data to my database only if it doesn't already exist. While attempting this, I encountered an error message: { [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false } My ...

Troubleshooting a mysterious anomaly with a jQuery UI button

Would like to achieve something similar to this: http://jqueryui.com/demos/button/#icons When trying to replicate it, http://jsfiddle.net/p5PzU/1/ Why is the height so small? I expected a square shape but am getting a rectangle instead. What could be c ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Showing time on a JSON document using JavaScript Timeline

Currently, I am in the process of creating a widget using a timeline JS template. The main challenge lies in receiving events in JSON format, which is essential for the functionality of the widget. At this stage, my focus is on being able to fetch events f ...