function escapeSpecialChars(str) {
  return str.replace(/\W/g, '\\$&');
}
Escape special chars for regular expressions

@param {String} str Regular expression to be escaped
@returns {String} Escaped version