Oleg Kovalov
Oleg Kovalov

Reputation: 762

Find the number in line. Javascript

How do I find the number in line number may not be in the beginning. For example: "d: \ \ 1.jpg"

Thank you.

Upvotes: 0

Views: 158

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075149

You can use a regexp:

var match = "testing 123".match(/\d/);
if (match) {
    alert(match.index); // alerts 8, the index of "1" in the string
}

That uses String#match, passing in a literal regexp using the "digit" class (\d).

And/or you can grab all contiguous digits starting with the first digit found:

var match = "testing 123".match(/\d+/);
if (match) {
    alert(match.index); // alerts 8, the index of "1" in the string
    alert(match[0]);    // alerts "123"
}

Those links are to the Mozilla documentation because it's fairly good, but these are not Mozilla-specific features.

Upvotes: 1

Oded
Oded

Reputation: 499182

You use a Regular Expression with the RegExp object:

var myRegEx = /\d+/; // RegEx to find one or more digits

var myMatch = myRegEx.exec("d:\\1.jpg")

Upvotes: 1

Related Questions