String substituion with Regex - can it be done without `.replace()`?

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'))
EEUUEEAEEAEEEEUU
EEUUEEAEEAEEEEUU
1 Like

If I’m reading this correctly it is taking all the vowels from the input string then returning the vowels and es and us are doubled.

You can use loops, conditionals, and arrays to achieve this.

Like one would not know that, already? This question is specifically about Regular Expressions. Read the question before giving an answer.

1 Like

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:

1 Like

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.

Unfortunately, that article’s at pretty much the extent of my regex knowledge…

On this you are spot on. Sorry for blowing past it.

1 Like

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.

1 Like

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…)

1 Like

That article mentions back references. That’s where we can start. The substitution part is what’s totally evading me. Still, dog needs a walk…

1 Like

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.

1 Like

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.

1 Like