0

As a JavaScript beginner I was reading Beginning Javascript (5th edition) by Jeremy McPeak and I saw something about regular expressions I just could not wrap my head around. It's this code:

var myString = "This sentence has has a fault and and we need to fix it."
var myRegExp = /(\b\w+\b) \1/g;
myString = myString.replace(myRegExp,"$1");
document.write(myString); /* this was added by myself to see the result in browser */

Could anyone explain exactly how it is that the myRegExp variable targets exactly the duplicate words in the myString variable once and not other words? Because from what I can read, this would be my interpretation of the regular expression variable myRegExp broken down piece by piece:

/  /* begin regular expression*/
(  /* start grouping pattern*/
\b /* beginning boundary character*/
\w /* any characters of a-z and 0-9 */
+  /* one or more instances of the previous characters, in this case \w. whether it has one "a" character or 5 characters like "apple" or even more characters */
/b /* ending boundary character*/
)  /* end grouping pattern */
\1 /* group 1 of regular expression */
/  /* end regular expression */
g  /* global search for the regular expression */

So the regular expression translated says: find any string pattern that starts with a boundary character (start of word) with 1 or more characters (unknown limit) which ends with a boundary character (end of word) and a empty space.

There is also a space before the \1/g which apparently is necessary for the code to work, but why exactly? How does the myRegExp variable not also target other words in the myString variable except the duplicate words since w+ part targets any words with 1 or more characters a-z and/or 0-9? And why does replace the + with * remove all spaces between the words?

Also, how should I read the "$1" part? Replace the found regular expression with group 1 and place it at the end? Wouldn't the command have no use since you would replace the found pattern with itself? I'm very confused about this all.

If anyone could explain this to me with an example, I would appreciate it very much!

None Cares
  • 17
  • 1
  • I'd suggest just reading up on back references (the `\1` thing). Do a Google search for "javascrip regexp back reference" and I'm sure you'll find useful stuff. –  Jun 30 '16 at 15:47
  • Sorry, I did not know this question was asked before. I will read up on back references. Thanks! – None Cares Jun 30 '16 at 16:59

0 Answers0