Convert integers in string to next number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • useroforacle
    New Member
    • Jan 2009
    • 1

    Convert integers in string to next number

    I am new to javascript and i have a requirement as follows:
    I have a varchar field for eg., 1234567890. I want to replace 1 with 2, 2 with 3.. 9 with 0..0 with 1 and so..
    How can i do this using javascript..
    Can anybody please post some code for doing this..
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Take each integer character from the string, then use parseInt to convert to an integer, add one unless it's 9 and then add to a temp string which you can return at the end of the function.

    Comment

    • mrhoo
      Contributor
      • Jun 2006
      • 428

      #3
      You could also use a string replace, with a function argument:
      Code:
      str= str.replace(/\d/g, function(n){
          if(n== '9') return '0';
          return ((+n)+1)+'';
      })
      prefixing a digit with a plus sign coerces a number, adding the empty string returns the incremented integer as a string.
      Last edited by Dormilich; Jan 14 '09, 01:50 PM. Reason: added [code] tags

      Comment

      Working...