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

Try the following:
.replace(/([&<>"' !@$%()=+{}\[\]])/g, '&#' + '$1'.charCodeAt(0) + ';')
(note: the back-single-quote after "' was removed by the board since I used the preformat option)

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) + โ€˜;โ€™)

del
Contributor III

Hah! @tstack, I was trying to beat you to the best answer and you still schooled me! ๐Ÿ™‚

tstack
Former Employee

@del I appreciate the effort, keep it up! Of course, it would be even better if we could improve the platform to the point where people didnโ€™t need to ask so many e-lang questions. Any ideas are welcome.