Why does my code work? :o(

Results 1 to 2 of 2

Thread: Why does my code work? :o(

  1. #1
    Dan Evans Guest

    Default Why does my code work? :o(

    For once I&#039d like my program to fail, but it doesn&#039t. Can someone explain why it works? It a simple string reversal using a regular expression. It takes each letter in turn and replaces it with the appropriate letter from elsewhere in the string.<BR><BR>var str = "Dan Evans";<BR>alert(str.replace(/(.)/g, <BR> function ($1, $2, $3) { <BR> return str.charAt(str.length - $3 - 1); <BR> })); // $3 is the index of the letter we&#039re replacing<BR><BR>The problem is that it displays the string reversed, but I don&#039t know why! After cycling through 3 letters, str would be "sna Evans". You can see that the "Dan" part would have vanished completely, so where does it get it from when it comes to swapping the last 3 letters? I would expect the final output to be "snavEvans". I&#039m going to be confused all day now :o(<BR><BR>-Dan Evans<BR>

  2. #2
    Dan Evans Guest

    Default Oh, I think I figured it out

    Since the result of the replace is not actually stored in str, I would imagine the results are being stored in a temporary variable before being returned to the alert. So while it does get the character from str, it doesn&#039t actually replace it.<BR><BR> Which I should have realised from the value of str being the same before and after the line. Don&#039t look at me like that - It&#039s a thursday morning! No-one thinks clearly on thursdays!<BR><BR>-Dan Evans (Fugged up)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts