2

I have following text:

The simple question, “What do you want to be when you grow up?” used to be fun to answer when we were all young. An astronaut, a princess, a superhero, a wizard were all perfectly plausible career’s to choose as a kindergartener. Once we get older that question becomes more of a serious matter and requires more thought and planning. It is no longer a subject that is fun to think about.
That simple question will no longer be satisfied with a random silly answer. What he or she chooses do with one’s life is a difficult, major decision.

I want to select the word 'do' proceeding by 'chooses'. For this I used following regex:
/(\bchooses do)/
But it selects the word "chooses do". How can I select only the word 'do' preceding by chooses.

Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36
  • 1
    `yourMatchString.split(" ")[1]` but I know why two steps?.. lets do the complete in one step using regex.. – Mr_Green Mar 11 '14 at 11:54
  • What are you trying to do exactly? – Jerry Mar 11 '14 at 11:55
  • http://www.commitstrip.com/en/2014/02/24/coder-on-the-verge-of-extinction/ – sdespont Mar 11 '14 at 11:56
  • split(" ")[1] gives the do string. But I want to select the do preceding by chooses. – Ganesh Kunwar Mar 11 '14 at 11:56
  • I want to replace the word 'do' preceding by choose not other word 'do'. – Ganesh Kunwar Mar 11 '14 at 11:57
  • If you are looking for groups in JS regexes, take a look at this question : [http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression](http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression) – Tejas Kale Mar 11 '14 at 12:01

2 Answers2

4

You can select only part of the matched phrase, for example: /chooses (do)/

This tool may help.

To actually replace the text, String.replace can take a callback which receives your regex matches as arguments, so you could do this:

text.replace( /chooses (do)/, function(match, group1) { 
    return 'chooses to ' + group1;
} );

Which would change 'Bob chooses do nothing' to 'Bob chooses to do nothing'.

djb
  • 5,591
  • 5
  • 41
  • 47
  • The main functionality is just like that you show in the link. But replace functionality so complex. It accepts the regex that select the word 'do' after 'chooses'. – Ganesh Kunwar Mar 11 '14 at 12:14
1

If you want to replace the word do with something else, then use something more like this:

var newword = "go";
newtext = text.replace(/\bchooses do/g, "chooses " + newword);
Jerry
  • 70,495
  • 13
  • 100
  • 144