/    Sign up×
Community /Pin to ProfileBookmark

Finding the first number in a string.

I’m wondering if there’s some sort of built-in function that finds the first number in a string. For example, I would want ‘var2_w5’ to return 2. I tried parseInt and parseFloat, which I don’t know much about, but they both returned ‘NaN’.

Or would I have to do a loop that goes through the string until it finds a number?

Thanks, Alan.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@khalidali63Jan 25.2003 — JavaScript does not have any buil in methods that will strip a or any number from a string for you.

You will have to parse throught the string and find the first or Nth number.

you can use charAt(n)

and see if its the first instance of number then break the loop

Khalid
Copy linkTweet thisAlerts:
@CharlesJan 25.2003 — [font=monospace]<script type="text/javascript">

<!--

String.prototype.firstNumber = function () {return this.match(/d+.?d*/)}

alert ('var2_w5'.firstNumber())

// -->

</script>[/font]
×

Success!

Help @AntonioMainenti spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...