I am trying to figure out what “$&
” do in the first replace (/[^aeiou]+\w*/, '$&way' )
. I am familiar with using $
when there is a grouping ()
in the regex. Since there is no grouping in the regex, I am a bit confused. I can’t find anything online to help me make sense of what is happening here. The second replace makes perfect sense to me .replace(/(^[^aeiou]+)(\w*)/, '$2$1ay')
. Using $
to change the group position. Just looking for some clarification on the first replace. I tried breaking down what was happening into parts (below) to try and make sense of what $&
did when combined but got nothing. Thanks
//str.replace(/[^aeiou]+\w*/, '$' ) = a$
//str.replace(/[^aeiou]+\w*/,'&') = a&
//str.replace(/[^aeiou]+\w*/, '' ) = a
//str.replace(/[^aeiou]+\w*/, '$&' ) = original string "algorithm"
function translatePigLatin(str) {
let regEx = /^[^aeiou]+/
let string = str
return str
.replace(/[^aeiou]+\w*/,'$')
.replace(/(^[^aeiou]+)(\w*)/, '$2$1ay')
}
console.log(translatePigLatin("algorithm"));
//str..replace(/[^aeiou]+\w*/,'$') = a$
//str.replace(/[^aeiou]+\w*/, '$&way' ) = algorithmway
//str.replace(/[^aeiou]+\w*/, '' ) = a
//str..replace(/[^aeiou]+\w*/,'$') = a$
//str..replace(/[^aeiou]+\w*/, '$&' ) = original string "algorithm"
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Pig Latin
Link to the challenge: