Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Last number in string

Reply
Thread Tools

Last number in string

 
 
aliensite
Guest
Posts: n/a
 
      11-21-2005
How do I get expression to output "24"?

<script>
var str = "dog3cat24z"
var re = /\D/g;
var lastNum = str.replace(re, "") // lastNum should be 24
document.write(lastNum)
</script>

Thanks

 
Reply With Quote
 
 
 
 
Evertjan.
Guest
Posts: n/a
 
      11-21-2005
aliensite wrote on 21 nov 2005 in comp.lang.javascript:

> How do I get expression to output "24"?
>
> <script>
> var str = "dog3cat24z"
> var re = /\D/g;
> var lastNum = str.replace(re, "") // lastNum should be 24
> document.write(lastNum)
> </script>
>


str = "dog3cat24z"

var lastNum = str.replace(/.*?(\d+)[^\d]*$/,'$1')

alert(lastNum)


--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

 
Reply With Quote
 
 
 
 
Dr John Stockton
Guest
Posts: n/a
 
      11-22-2005
JRS: In article <(E-Mail Removed) .com>
, dated Mon, 21 Nov 2005 14:36:08, seen in news:comp.lang.javascript,
aliensite <(E-Mail Removed)> posted :
>How do I get expression to output "24"?
>
><script>
>var str = "dog3cat24z"
>var re = /\D/g;
>var lastNum = str.replace(re, "") // lastNum should be 24
>document.write(lastNum)
></script>


If there is always a non-digit before the last number - and you can
assure that by prepending one -
lastNum = str.replace(/.*\D(\d+)\D*/, "$1")

This might work without that condition, but in fewer browsers -

lastNum = str.replace(/.*?(\d+)\D*/, "$1")

Also

lastNum = str.split(/\D+/).reverse()[0]

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
convert string number to real number - ValueError: invalid literal davidj411 Python 11 05-29-2008 12:02 AM
How to replace the last (and only last) character in a string? Johny Python 8 05-03-2007 09:24 PM
OT: Number Nine, Number Nine, Number Nine Frisbee® MCSE 37 09-26-2005 04:06 PM
HELP - how to convert a string representation of a number to a number ? cpptutor2000@yahoo.com C++ 5 05-21-2005 05:56 PM
Interrogating string for number of characters, response.writing identical number of characters on new line Ken Fine ASP General 2 02-05-2004 03:40 AM



Advertisments