Alex
Alex

Reputation: 19803

replace Nth word in javascript using regex

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");});

Upvotes: 2

Views: 1693

Answers (1)

SethB
SethB

Reputation: 2090

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.

Upvotes: 2

Related Questions