Somewhere along the way one is sure we learned how to do substitution with a Regular Expression, alone, without the aid of a string method. Maybe I’m wrong; memory sometimes deceives me.
Is there a way to write this without using the replace() method?
const whaleTalk = function (s) {
return s.replace(/[^aeiou]/ig, '').replace(/e/ig, 'ee').replace(/u/ig, 'uu').toUpperCase()
}
console.log(whaleTalk('THE HUNGER GAMES HAVE BEGUN'))
console.log(whaleTalk('the hunger games have begun'))
I’m afraid this possible(?) solution comes from the old Google (and in the form of a link). I imagine this isn’t quite the approach to problem solving that you’re looking for, so I’ll blur the link to the article:
Yeah, only thing is narrowing on a response to this example is sketchy. I think the vagueness of the question stems from the need of a method to process the regex, whether replace or match, &c. We could be grasping at straws. The thing to do now would be find a way to reduce the example above to a single replace() if that is even possible. Might be it’s as simplified as it can be. Don’t know, can’t say, hence this question.
We’re in the same boat, I’m afraid. What kills me is how simple the language and yet so inimitably ingrained. The pattern exists, we just have to put our finger on it. Like chess all over.
I know the feeling all too well! I suppose the question is looking for a complete lack of string methods, not just a lack of regex-based methods? (Either way, I still haven’t much of a clue…)
Barring submitted improvements, the sample stands as the return line of this function. That is, unless someone objects to using the regular expression engine. They could make a valid argument if this didn’t scale correctly.
This isn’t exactly what you’re looking for, but you can pass in a function to .replace(), thereby eliminating the need for multiple calls to that string method.
For example, something like this:
function whaleTalk(s) {
return s.replace(/[a-z\s]/ig, (m) => { return (m.match(/[eu]/i) ? m + m : m.match(/[^aeiou]/i) ? '' : m).toUpperCase() })
}
But that’s pretty ugly and I wouldn’t say it’s any better than .replace() three times.