#1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    754
    Rep Power
    123

    String replace error


    In an effort to replace a leading zero I attempt:
    function Age() {
    var bday;
    bday = parseInt(document.forms[0].txtBday.value);
    alert(bday.replace(/0(\d\/)/g,'$1')); ...
    and I receive an error saying that replace is not a function.
    I am trying to remove a leading zero but why isn't replace a function?

    I thought that parseInt would convert the string to an integer and get rid of the leading zero.

    Thanks,

    Comments on this post

    • Arty Ziff agrees : Spread the wealth! Give rep liberally!
  2. #2
  3. Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Dec 2003
    Posts
    2,343
    Rep Power
    581
    You're right - parseInt converts the string to an int, and ints have no replace() function
    (only strings do)!

    So, just convert it back to a string if you want to use the replace:
    Code:
    bday=''+bday;
    or similar.

    Comments on this post

    • haydenchambers agrees : fast typing
    • Arty Ziff agrees
  4. #3
  5. hack of all trades
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2009
    Location
    Madrid
    Posts
    898
    Rep Power
    520
    replace is a string function and your bday is was converted to a number with the parseint
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2009
    Location
    Scotland
    Posts
    15
    Rep Power
    0
    Why not do the replace on the value of the text field, BEFORE you do parseInt ?
    I must admit to being surprised that parseInt would leave you with a leading zero anyway...
  8. #5
  9. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2003
    Posts
    802
    Rep Power
    104
    The parseInt function assumes that numbers with leading zeroes are given in octal notation! For instance, alert(parseInt("010")); alerts 8.

    Use this instead:

    Code:
    function Age() {
      var bday;
      bday = Number(document.forms[0].txtBday.value);
    This will get rid of the leading zero.
  10. #6
  11. hack of all trades
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2009
    Location
    Madrid
    Posts
    898
    Rep Power
    520
    or specify the base eg parseInt(x, 10)

    Comments on this post

    • Arty Ziff agrees : Spread the wealth! Give rep liberally!

IMN logo majestic logo threadwatch logo seochat tools logo