Forum Discussion

walkerline117's avatar
walkerline117
Contributor
8 years ago
Solved

Best way to escape special char of html

Hi, I would like to escape special HTML characters of a string. e.g. <>,',",@ etc… I know i can use ‘replace’ method to replace all of those characters one by one with the encoded ones, but is th...
  • tstack's avatar
    tstack
    8 years ago

    The second parameter can be a function, but there’s a bug caused by the regex not having escapes for the square brackets. Del’s version of the regex works:

    However, the second parameter is going to replace with the char code for ‘$’ and not the character that matched the regex. The second parameter needs to be an arrow function, like so:

    .replace(/([&<>"'` !@$%()=+{}\[\]])/g, x => ‘&#’ + x.charCodeAt(0) + ‘;’)