DEV Community

Discussion on: 9 Extremely Powerful JavaScript Hacks

learnbyexample profile image

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. 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:

razgandeanu profile image
Klaus Author

Thank you for sharing that with us.