JavaScript: Replace Special Characters in String from a Hash Table
Using replace() with regex, hash table and arrow function expression
$ sudo ./replChars.js
'<h2>Hello World!<h2>'
The hash table contains key/value pairs. Those values will be used to replace matching special characters:
d = { '<': '<', '>': '>' }
Two parameters are passed to replace()
:
/<|>/g
(regex pattern)x => d[x]
(arrow function expression)
The arrow function expression calls replace()
to compare each character with the regex pattern. If a match is found, the matching character is replaced with the hash table value.
In a Node.js REPL:
> d = {'<':'<','>':'>'}
{ '<': '<', '>': '>' }
> s = '<h2>Hello World!</h2>'
'<h2>Hello World!</h2>'
> s.replace(/<|>/g, x => d[x])
'<h2>Hello World!</h2>'
For further instruction, visit the page linked below: