"replaceAll is not a function". Is that so?

Why do you think I see this weird message “replaceAll is not a function”? It definitely is!

When I call replaceAll with your arguments, I get a slightly different error message:

String.prototype.replaceAll argument must not be a non-global regular expression

Try calling replaceAll with a g modifier for the regex, works for me then:

.replaceAll(/\s/g,'*')

From the mdn docs:

Global flag required when calling replaceAll with regex

Yeah, I read that requirement about the necessity of the global flag though it didn’t help me

Also. as a bonus question, why would I need replaceAll() if I can include the global flag in a regular replace() and get the same result? :thinking:

Who says you do?

There’s a difference between both methods is you use a string rather than a regex as first argument:

console.log('ha ha ha'.replace(' ','*')) // "ha*ha ha"
console.log('ha ha ha'.replaceAll(' ','*')) // "ha*ha*ha"

Just saves some typing, I guess. No need for a regex if you have such a simple pattern…

But if I use regex, it’s all the same, isn’t it?

Not quite. You can use replace with a regex for the replacement of the first occurrence:

console.log('ha  ha ha'.replace(/\s+/,'*')) // "ha*ha ha"
console.log('ha ha ha'.replaceAll(/\s+/g,'*')) // "ha*ha*ha"

But there’s no need for using replaceAll with a regex, I guess.

1 Like