Breaking down a string using JavaScript

Is there a way to shorten the following code? It currently works for me, but it seems quite long-winded.

var str = "some title of an event here, weekday 17:00 – 18:00 o’clock, with name of a person";
var date = str.split(', ');
var time = date[1].split(' ');
var timeItems = time[1].split('–');
var startTime = timeItems[0].trim();
var endtime = timeItems[1].trim();
alert("event lasts from "startTime + " to " + endtime);

Any suggestions on how to make this more concise would be greatly appreciated. Thank you!

Answer №1

Are you only interested in extracting the startTime and endTime? If that's the case, a simple solution would be to use the split() method on the colon character:

times = str.split(':');
startTime = times[0].slice(-2) + ':' + times[1].slice(0,2);
endTime = times[1].slice(-2) + ':' + times[2].slice(0,2);
alert("event duration is from " + startTime + " to " + endTime);

Answer №2

While you may find regexes to be unnecessary at times, they can definitely come in handy when trying to condense your code:

let str = "event details: start time 17:00 – end time 18:00, hosted by John Doe";
let times = str.match(/\d\d?:\d\d/g);
alert("the event runs from " + times[0] + " until " + times[1]);

You can test it out here: http://jsfiddle.net/jvs3s/

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

Attempting to transform a callback-dependent function into one compatible with generators (using yield) proves to be unsuccessful

Trying to synchronously invoke a regular call-back style function in koa using generators. This method has been successful: var output = yield function (cb) { myDaoObject.load(function (err, res) { cb(err, res); }) }; Now, attempting t ...

Cut the string at "_B"

For some reason, this line of code is not functioning properly and I am unsure as to why: String[] stringHolder = string.split("_(B"); An error stating "Unclosed group near index 3" appears when I try to run the above code. In contrast, this line of ...

Building a responsive image gallery modal using AJAX in Laravel platform

How can I fix the issue of the modal content briefly appearing when I load my page? I am trying to create an image gallery where a modal opens when an image is clicked. Here is the code in my view.blade.php: <script> $(".li-img").click(function ( ...

Multiple buttons in a single field

I am attempting to replace a Dropdown list with a series of buttons that will streamline the choices previously displayed by the dropdown list. Specifically, we are using graphic png files for the types of buttons. We experimented with checkboxing and ra ...

Adjust the color of the sidebar's list items when scrolling

How can I change the background color of left sticky sidebars li on scrolling? When scrolling through BMW, BMW's background color in the sidebar should turn green. Please refer to the code snippet provided below. The background color of the li ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

Receiving a JavaScript object from an on-click event and passing it to a function does not allow it to be submitted as part

Appreciate any insights... I handle the submission of a form button click: $('.saveItem').on( 'click', function(e) { submitItemSave(true, e); }); When the user-defined function is called on click, the event, e, is passed in: func ...

Understanding the proper way to enclose JSX components and exhibit JSON based on user input

I'm currently working on a university administration website using React that needs to support multiple languages. I have successfully built the Login page, which you can see here: https://i.stack.imgur.com/cIiaU.png Now, my next task is to allow us ...

What is the best way to transmit data to a PHP script using AJAX?

I'm facing an issue with my basic ajax script not running. The code I have should work fine. The ajax script is: <html> <head><title>Testing ajax</title> <script type="text/javascript"> function ajax() { ...

Select a random character from a string using JavaScript

This question sets itself apart from Removing random letters from a string as it focuses on selecting a random letter from a string in JavaScript without removing any characters. The goal is to implement a code that picks random letters from a string in J ...

What could be causing the malfunction of AngularJS $scope?

I recently started using AngularJS and I'm trying to create an array and send it to the server using the register function. Below is the Controller code snippet: root.controller('mainController', function($scope) { $scope.lineItems = [ ...

The error message "Seed is not defined" is raised when the program attempts to

I'm currently diving into fullstack vue and I'm perplexed by the error occurring in this particular scenario. window.Seed = (function () { const submissions = [ { id: 1, title: 'Yellow Pail', ...

Transforming a JSONP request to automatically parse a text response into JSON

If I have the following request $.ajax({ type: "GET", dataType: "jsonp", jsonp: "callback", jsonpCallback: "my_callback", url: my_https_url, headers:{"Content-Type":"text/html; charset=utf-8"}, success: function(data) { ...

When it comes to utilizing jQuery for the mobile view, how many jQuery libraries are recommended for optimal performance?

I'm currently constructing a website using ROR, and for the mobile view, I've implemented the mobile_fu gem. The designer provided me with a design for the mobile view that includes various jQuery sliders, players, image sliders, drop-down menus ...

Extracting individual rows of data from a text file and storing them in separate arrays

Survey data is currently stored in a text file and needs to be organized into separate arrays. An example of the data format is: C 1 1000 1000 C 2 1010.72 1005.04 ...

I aim to generate a JavaScript string that, when placed within a div tag, will display as a list

I need assistance with formatting a string that contains a list of items to display in a specific way within a div tag using JavaScript. The string has multiple items that I wish to show as a bulleted list. Here is an example of the string: const items = & ...

What is the best way to attach information to a chart prior to the jquery dialog box appearing?

I am currently working on a web application that interacts with an Azure database. The goal is to create a graph based on user selections from a radio list and two inputted time parameters. The intention is to showcase this graph in a jQuery dialog box tha ...

Using an image as the background for a three.js scene may cause it to appear distorted

I am struggling with setting an image as a background for my scene without it becoming blurry. I have attempted to use the following code: textureLoader.load("images/background/space.png", function(t) { scene.background = t; }); The problem arises when ...

React: Unexpected behavior when modifying a variable's state using post-increment

When I utilize the post-increment operator to change the state variable, the count variable retains its old value... Allow me to illustrate this with an example app: When I click the button with the following code, the app displays the following sequenc ...