Last number in string

A

aliensite

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
 
E

Evertjan.

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)
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Mon, 21 Nov 2005 14:36:08, seen in
aliensite said:
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]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top