JavaScript: Replace Special Characters in String from a Hash Table

Using replace() with regex, hash table and arrow function expression

nick3499
1 min readMay 31, 2018

$ 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 = { '<': '&lt;', '>': '&gt;' }

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 = {'<':'&lt;','>':'&gt;'}
{ '<': '&lt;', '>': '&gt;' }
> s = '<h2>Hello World!</h2>'
'<h2>Hello World!</h2>'
> s.replace(/<|>/g, x => d[x])
'&lt;h2&gt;Hello World!&lt;/h2&gt;'

For further instruction, visit the page linked below:

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet