DEV Community

Discussion on: 9 Extremely Powerful JavaScript Hacks

Collapse
learnbyexample profile image
Sundeep

The replace all trick with regexp will work only if string to search doesn't contain regexp metacharacters like ., ^, etc. You'll have to escape them first. developer.mozilla.org/en-US/docs/W... provides an escape function.

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

'abc a;c a.c apc a.c'.replace(/a.c/g, 'X')
// gives "X X X X X"

'abc a;c a.c apc a.c'.replace(new RegExp(escapeRegExp('a.c'), 'g'), 'X')
// gives "abc a;c X apc X"

String.prototype.replaceAll is proposed to avoid such issues: github.com/tc39/proposal-string-re...

Collapse
razgandeanu profile image
Klaus Author

Interesting.
Thank you for sharing that with us.