user3044394
user3044394

Reputation: 135

find multiple digits and a colon within a string using regex

I'm trying to find any string of digits followed by a colon. Here is an example string:

var str = "  234:  all kinds of code";

Here is what I tried:

str.search(/^\d+:$/);

and that returns a -1 so it is not finding the digits followed by the colon.

I tried this and it returned 0:

/^.+\d+:.+$/

Upvotes: 1

Views: 634

Answers (3)

James McGuigan
James McGuigan

Reputation: 107

Use this website to verify your reg exs. I use it all the time

Regex101

Drop your ^ and $ or place wildcards around your "\d+:"

Upvotes: 1

Your regex is only successful when the string to search begins and ends with digits followed by colon. Try this:

str.search(/\d+:/);

Upvotes: 1

Hagen von Eitzen
Hagen von Eitzen

Reputation: 2177

Drop the ^ (matches only beginning of string, but your number is somewhere in the middle) and the $ (matches only end of string, but there is text after the colon) from your regexp.

Upvotes: 1

Related Questions