cancel
Showing results for 
Search instead for 
Did you mean: 

Best way to escape special char of html

walkerline117
Contributor

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 there any better way to do this in a mapper with expression?

BTW, I tried to use replace like this
.replace(/[&<>"'` !@$%()=+{}]/g, function(x){ return ‘&#’ + x.charCodeAt(0) + ‘;’})

but the mapper keeps throwing me errors as it seems the second parameter of the replace method cannot be a function?

Thanks

1 ACCEPTED SOLUTION

tstack
Former Employee

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) + ‘;’)

View solution in original post

5 REPLIES 5

del
Contributor III

@tstack, I’m not sure the appropriate category, but to avoid hijacking this thread, (in a few minutes) I’ll start a post of ideas in the Enhancement Requests category.