Discovering the position of digits within a string using Javascript

Could someone help me find the positions of the numbers (1994 and 27) within this string?

I attempted to split the string but I'm unsure about how to proceed from there.

let str = 'year of birth: 1994, and i'm 27 yo'

Answer №1

Easy method for locating index

function locateIndex(str) {
        var number = /\d/;
        var numbers = str.match(number);
        return str.indexOf(numbers);
    }

console.log(locateIndex('The year is 2021'));//outputs 12

Answer №2

Once the string has been divided, simply iterate through it and determine if each element is numeric or not.

let str = "year of birth : 1994 , and i'm 27 yo";
strArray = str.split(' ');
    for(let i=0;i<strArray.length;i++){
        //Check using isNaN() whether the element is a number.
        if(isNaN(strArray[i])==false){
            console.log("Number "+strArray[i]+" is at index "+i);
        }
    }

Answer №3

If you're looking for a quick and convenient method, give the search() function a try.

Here's how it works:

str.search(regex);

In this syntax, str refers to the string you want to search within, and regex is what you're searching for.

The output: indicates the first occurrence index of your target element, such as a number in this case. You can then decide how to utilize this index, like slicing the string from that position.

To effectively use this method, it's vital to have a good grasp of regular expressions, which require some additional knowledge beyond the basic usage.

For instance:

let str = "year of birth : 1994 , and i'm 27 yo";
let reg = /\d/;
let ind = str.search(reg);
alert('the first instance of "'+reg+'" is found at index: ' + ind);
// The expected outcome here is 16 since it's where the number (1) appears in 1994;

// If you need to search for a specific number instead of any digit,
// adjust the reg variable accordingly. Let's find 94 for example..
reg = /94/;
ind = str.search(reg);
alert('the first instance of "'+reg+'" is found at index: ' + ind);

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

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

Looking to halt navigation in a Chrome browser immediately after performing a click action with Selenium?

Is there a way to prevent the browser from loading immediately after a click event? Are there any workarounds or JavaScript implementations for achieving this? ...

When using VueJs, the input value may not clear upon pressing the ESC key for the first time

When I press the ESC key, my input should clear. However, I am experiencing a bug where the input is not cleared after the first press of the ESC key; it only clears after the second press. Even though the console displays an empty value for the input aft ...

After stopping the interval with clearInterval(), you can then use the res.send method

I need to continuously log the current date and time to the server console then stop logging after a specified time, returning the final date and time to the user. How do I properly utilize ClearInterval() in this scenario? const express = require(" ...

What could be the reason behind an Ajax Auto-Complete feature suddenly malfunctioning when moving to a new page within the same website?

Working on a website featuring an auto-complete search box powered by Ajax, Javascript, and PHP. As the user types into the search box, an ajax request triggers a php file to query a database and return possible results. Everything works smoothly until the ...

iOS creates dynamic images with artifacts that appear on a generated and animated canvas

I am currently developing an HTML5 web application for WeChat, compatible with both iOS and Android devices, using only pure JavaScript without any third-party libraries like jQuery. The main feature of my app involves creating visually appealing animation ...

I'm looking for guidance on the syntax of declaring a constant variable with an empty object in JavaScript. Can someone please explain or

Can you explain the meaning of this JavaScript syntax (likely in ES6)? const {} = variablename; I've been diving into React lately and noticed this syntax used in many examples. For instance: const {girls, guys, women, men} = state; ...

Adding JSON data to an array with a click - a step-by-step guide

As I dive into working with React and integrating API JSON data into my project, I've encountered a small hurdle. I've implemented a function that allows users to enter a search query, resulting in a list of devices associated with their input be ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

Which specific page initiates the post request?

Seeking help with my post request that originates from a specific page on my website: reqdata = 'text=' + mytext; $.ajax({ type: "POST", url: "/request.php", data: reqdata, cache: false, success: function(html) { alert(html) } ...

Ways to Retrieve the Index of Elements in the DOM Array Generated by the querySelectorAll() Function in JavaScript

const items = document.querySelectoAll('.class') console.log(items) // Array with 15 elements (This array contains a total of 15 elements) ...

Experiencing an error message of "undefined" when attempting to retrieve a value from outside

While working with Node.js, I utilized a request to fetch some data from an API. However, when I attempted to access these values outside of the function braces, they returned undefined. var tab_det; request.post({url:'https://ludochallenge.com/i ...

The features of findOneAndRemove and findOneAndUpdate are not functioning optimally as expected

Attempting to create a toggle similar to Facebook's "like" feature. The code functions correctly when there are no existing "likes." It also deletes properly when there is only one "like" present. However, issues arise when multiple likes accumulat ...

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

What is the correct method for compiling a list of users?

Hello, I have developed a basic user list based on database results, but I am facing two issues with it. Currently, my list displays like this: [UserOne, ...][UserTwo, ...] However, I need the format to be: [UserOne],[UserTwo]... The three dots repres ...

AWS Lambda optimizes variable initialization by reusing values from previous executions, eliminating the need to reinitialize

Currently, I am encountering a problem while deploying an AWS Lambda Function for numeric calculations. The issue arises when the function is initially deployed and runs correctly, but subsequently it starts taking previous values into account and recalcul ...

Saving information using Socket.io server during the 'connect' event

Currently, I am working with socket.io along with MongoDB and promises. My goal is to save some data in Mongo when the session is established so that further socket events cannot be properly handled until this data is successfully saved. // Below is my si ...

What is the best way to group data by a specific value within a nested object when using ReactJS material-table?

I have a unique scenario where I possess an array of individuals featuring a nested object known as enterprise. My objective is to effectively group these individuals by the value of company.name within the confines of the Material-Table. const people = [ ...

Loop over elements retrieved from Firebase using ng-repeat

I am currently attempting to iterate through items retrieved from Firebase using ngrepeat. Although I can see the items in the console, the expressions are not working as expected. I have tried various solutions, but nothing seems to be working. Any assist ...

How can I automatically select an option in Vue JS based on a nested v-for value?

I am encountering a challenge with a nested v-for inside of another v-for in my Vue project. Although I am able to retrieve the correct data, I am facing difficulty using a select dropdown to populate a field and automatically selecting the option based on ...