Last number in string

Discussion in 'Javascript' started by aliensite, Nov 21, 2005.

  1. aliensite

    aliensite Guest

    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
    aliensite, Nov 21, 2005
    #1
    1. Advertising

  2. aliensite

    Evertjan. Guest

    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)
    Evertjan., Nov 21, 2005
    #2
    1. Advertising

  3. JRS: In article <>
    , dated Mon, 21 Nov 2005 14:36:08, seen in news:comp.lang.javascript,
    aliensite <> 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.
    Dr John Stockton, Nov 22, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    5
    Views:
    511
    Pete Becker
    May 21, 2005
  2. sangram
    Replies:
    16
    Views:
    1,966
  3. Johny
    Replies:
    8
    Views:
    385
  4. davidj411
    Replies:
    11
    Views:
    1,275
    Kam-Hung Soh
    May 29, 2008
  5. Simon Strandgaard

    [rcr] String#first / String#last

    Simon Strandgaard, Oct 24, 2004, in forum: Ruby
    Replies:
    29
    Views:
    228
    Brian Candler
    Oct 26, 2004
Loading...

Share This Page