How to Find the Index of the First Number in a String Using JavaScript?

Estimated read time 1 min read

To find the index of the first number in a string in JavaScript, you can use a loop and the charCodeAt method. The charCodeAt method returns the Unicode code point value of the character at the specified index in a string.

Here’s an example:

const string = "Hello World 123";

let index = -1;

for (let i = 0; i < string.length; i++) {
  if (string.charCodeAt(i) >= 48 && string.charCodeAt(i) <= 57) {
    index = i;
    break;
  }
}

console.log(index); // Output: 11

In this example, a for loop is used to iterate through the characters in the string. The charCodeAt method is used to get the Unicode code point value of each character. If the code point value is between 48 and 57 (inclusive), which represents the ASCII code for the digits 0 to 9, then index is updated with the current index i and the loop is exited using the break statement. If the loop completes without finding a number, index remains at its initial value of -1.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply