2

I would like to replace the Nth word of a string with another word in javascript. For example:

<div id="sentence">This is some sentence that has the word is.</div>

Replace the second word of this sentence, is, with was leaving the is at the end untouched. I thought the following would work but it does not:

var p = new RegExp('(?:\\S+ ){1}(\\S+)');
$("#sentence").html(function(k,v) {return v.replace(p, "was");});
4
  • Does it say anywhere in that homework assignment(?) that you can not simply replace the first occurrence of is (looking for a word boundary before it, so that it doesn’t replace “this”), without caring about that it happens to be the second word? "This is some sentence that has the word is.".replace(/\bis/, "was") Commented Feb 16, 2015 at 20:52
  • yes this is just a simple example, in reality the thing i need to do is more complicated so it has to be second word rather than identifying the actual word. Commented Feb 16, 2015 at 20:54
  • is it going to be the second always? Commented Feb 16, 2015 at 20:56
  • no not second always Commented Feb 16, 2015 at 20:59

1 Answer 1

2

Use a capture group and add it to the replace value with $1

var p = new RegExp('^((\\S+ ){1})(\\S+)');
$("#sentence").html(function(k,v) {return v.replace(p, "$1was");});

Full example:

<!DOCTYPE html>
 <html>
  <head>
   <script
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
   </script>
  </head>
 <body>
  <div id="sentence">This is some sentence that has the word is.</div>
  <script>
   var p = new RegExp('^((\\S+ ){1})(\\S+)');
   $("#sentence").html(function(k,v) {return v.replace(p, "$1was");});
  </script>
 </body>
</html> 

Explanation:

^ Matches the beginning of the string.

(\\S+ ){n} Repeats n times, but this would also repeat the capture. (Keeping only the last group captured.)

((\\S+ ){1}) Embed the repeat inside a capture group. $1

(\\S+ ){1} This is now the second capture group. $2 Only the last iteration is stored in $2

(\\S+) Capture the extra word to be replaced. $3

v.replace(p, "$1was"); $1 adds the first capture group and back into the string. The second capture group is left out.

Sign up to request clarification or add additional context in comments.

2 Comments

awesome! can you explain the ((\\S+ ){1}) portion: specifically, how does regex treat embedded captures of this type?
(){3} Repeat capturing into $1 (Only last capture is retained) ((){3}) Repeat capturing into $2. Capture entire group in $1. Start counting groups by the (. The group still ends at the matching ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.