Weblurk
Weblurk

Reputation: 6812

How do I get the first word that starts with a number using regex and Javascript?

I can't figure out how to write a regex pattern that catches all words which begins after the first number. Two examples below for clarity:

var string1 = "Area 51"; // This is the string I have
var match1 = "51"; // This is the string I want

or this:

var string2 = "A simple sentence with 6 words or more" // This is the string I have
var matchedString = "6 words or more" // This is the string I want

Any ideas?

Upvotes: 0

Views: 444

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use regex \b\d+\b.*$ and method match() for pattern match

var string1 = "Area 51"; // This is the string I have
var match1 = string1.match(/\b\d+\b.*$/)[0];

var string2 = "A simple sentence with 6 words or more" // This is the string I have
var matchedString = string2.match(/\b\d+\b.*$/)[0]; // This is the string I want

document.write(match1+'<br>'+matchedString);

Regex explanation

\b\d+\b.*$

Regular expression visualization

Debuggex Demo

Upvotes: 5

Ozan
Ozan

Reputation: 3739

Use \b word boundary followed by \d to find a word starting with a number.

var str = "Simple test1 String 2where there rand3om number4s through5out.";
alert(str.match(/\b\d.*/)[0]);

Upvotes: 0

Related Questions