Register

If this is your first visit, please click the Sign Up now button to begin the process of creating your account so you can begin posting on our forums! The Sign Up process will only take up about a minute of two of your time.

Results 1 to 4 of 4
  1. #1
    Junior Member
    Join Date
    Dec 2007
    Posts
    6
    Member #
    16237
    I want to use replace() to change the last occurence of a word which isn't necessarily at the end of a line. For example, replace the last occurence of 'duck' with 'goose' in "duck duck duck goose" so that it becomes "duck duck goose goose".

  2.  

  3. #2
    Senior Member
    Join Date
    Jun 2005
    Location
    Atlanta, GA
    Posts
    4,146
    Member #
    10263
    Liked
    1 times
    Are these repetitions next to each other? That is to say, will they always be consecutive, or might there be words between them?

  4. #3
    Junior Member
    Join Date
    Dec 2007
    Posts
    6
    Member #
    16237
    There could also be words between them. I managed to find the solution afterwards:

    str1.replace(/(.*)duck/i, "$1goose")

    I have no idea how or why it works, but there you have it.

  5. #4
    Senior Member
    Join Date
    Jun 2005
    Location
    Atlanta, GA
    Posts
    4,146
    Member #
    10263
    Liked
    1 times
    Oh. Lol. I definitely thought there had to be at least one previous occurrence of the word. The reason it works, in case you're interested, is that regular expressions in Javascript are what we call greedy. That means that when you say (.*)duck, it will start eating characters until it hits the word `duck'. When it reaches that, it will make a note that it found `duck' there, and then it will continue eating characters until it finds `duck' again. If it doesn't, then it will `backtrack' to the first place it found it and then run the replace on that location. If it does, then it will mark the new place where it found it and then keep looking. Then, when you go to replace, the $1 represents everything before the last `duck'. So you're basically saying `pull everything up until the last `duck', then replace that part with everything before the last `duck' followed by `goose''.


Remove Ads

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
All times are GMT -6. The time now is 05:11 AM.
Powered by vBulletin® Version 4.2.3
Copyright © 2019 vBulletin Solutions, Inc. All rights reserved.
vBulletin Skin By: PurevB.com