What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning

I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a function to find the starting index of '#' and now need to extract only the numbers after '#'. Currently, I am using a for loop to iterate through the string to identify the number value. However, it seems that the return statement is executed prior to the completion of the for loop. How can I adjust this so that the return waits for the for loop to finish and update the internal variable before proceeding?...

  readNumber(text: string): number {
    const start = text.indexOf('#') + 1;
    let newText = '';
    for (let index = start; index < text.length; index++) {
      if (text.slice(index, 1) === ' ') {
        newText = text.slice(start, index - start);
      }
    }
    return +newText;
  }

If the user enters "employee #56 cv," I expect the output to be 56.

Answer №1

After assigning to newText, the loop will indeed continue. To halt it at that point, you can include a break:

newText = text.slice(start, index - start);
break;

Alternatively, you can bypass the loop entirely by utilizing indexOf once more:

readNumber(text: string): number {
  const start = text.indexOf('#') + 1;
  if (start === -1) {
      return 0; // You can specify another value to return when '#' is not found
  }
  let end = text.indexOf(' ', start);
  if (end === -1) {
      end = text.length;
  }
  return +text.substring(start, end);
}

You may also opt for a regular expression method:

readNumber(text: string): number {
  const match = /[^#]*#(\d+)/.exec(text);
  if (!match) {
      return 0; // You can define a different return value if '#' is absent
  }
  return +match[1];
}

This approach is slightly altered from your example as it captures a sequence of digits instead of looking for a space. If you prefer to use a space instead:

readNumber(text: string): number {
  const match = /[^#]*#([^ ]*)(?: |$)/.exec(text);
  if (!match) {
      return 0; // You can specify an alternative return value in case '#' is missing
  }
  return +match[1];
}

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

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

How can you temporarily stop an event with a click or touch, and then resume the event's state after performing certain tasks in jQuery?

Exploring options for tracking clicks with precision - interested in finding a way to defer the event propagation until a certain function completes. Any suggestions on an alternative approach or how to effectively delay the normal event flow? $(this).on ...

A guide on sending a post request with Axios to a parameterized route in Express

Recently, I set up an express route router.post('/:make&:model&:year', function (req, res) {   const newCar = {     make: req.params.make,     model: req.params.model,     year: req.params.year   }   Car.create(newCar);   res ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

A comprehensive guide on personalizing Bootstrap 4 tooltips to suit your specific needs

I would like to customize the tooltip in Bootstrap 4 based on the screenshot provided below: https://i.stack.imgur.com/wg4Wu.jpg <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta chars ...

Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements: COMPSCI20 ...

I'm looking to add autocomplete functionality to a text input in my project, and then retrieve and display data from a MySQL database using

Looking to enhance user experience on my form where users can select inputs. Specifically, I want to implement a feature where as the user starts typing in a text input field with data from a MYSQL database, suggestions will be displayed. The form is locat ...

Choose a phrase that commences with the term "javascript"

I need assistance in creating two unique regular expressions for the following purposes: To select lines that begin with 'religion'. Unfortunately, my attempt with /^religion/g did not yield any results. To match dates and their correspondi ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

When I navigate to the About page in Vue, the data is automatically cleared

Assist me, please! I am encountering an issue with my website. I have two main pages: Home and About, as well as a component called SecondPage. The SecondPage component contains two tables filled with data that should be displayed on the About page. Howeve ...

What is the best way to include a select HTML element as an argument in an onSubmit form function call?

I am currently facing an issue where I am attempting to pass HTML elements of a form through the submit function as parameters. I have been able to successfully retrieve the nameInput element using #nameInput, but when trying to access the select element ( ...

Vue.js is displaying one less item

Recently I started working with Vuejs and encountered an unexpected issue in my application. The purpose of my app is to search for channels using the YouTube API and then display those channels in a list. However, when I try to render the list of subscri ...

Is it possible to execute MongoDB queries from an AS3 client?

Can native Javascript functions for the mongo shell be run on server side from an AS3 client AIR app? I have experience running Javascript methods embedded/loaded in HTML where SWF is also embedded, and I'm curious if it's possible to make a ser ...

JavaScript OOP Function call not functioning in IE9

When using IE9, a JavaScript OOP Function call does not seem to work for me. Here is my code snippet: var newobj = new SAObject(); <input onclick="newobj.function()" /> Upon clicking the button, nothing happens. No alert is displayed, and it seem ...

Error: Uncaught promise rejection - The function is undefined in the context of Vue.js and Electron

I've been experimenting with anime.js to animate elements using promise functions. However, I'm encountering an issue where the second function does not run after the previous one successfully completes. <script> import Splash from '. ...

The next function is not defined error in the controller function

Everything was running smoothly until I suddenly encountered this error message: ReferenceError: next is not defined. I'm puzzled because I didn't make any changes to this function. const Users = require('../data/users.model') exports ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

Activate the HTML drop-down option upon selecting the radio button, or the other way around

I'm attempting to accomplish a task. Below is the code snippet I am working with: <form> <input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type=&apo ...

The dangers posed by vulnerabilities in the React library

Hi there, I just finished setting up react-redux and noticed some vulnerabilities showing up in my console - both low and high. Can anyone explain what this means and if I should consider uninstalling it? ...

Node.js server containerized with Docker: deleted express route remains accessible

I recently developed a Twitch Chat Bot using Dockerized (docker compose), Node.js v16 with express. To create an authorize-page for users to authorize my bot on the Twitch API, I utilized the route /auth/request: this.serverUrl = serverUrl; this.port = po ...