String replace in objects and arrays in Javascript

I think this is the longest title for a post so far! Well, best make it a good one then…

I recently came across a problem at work where I had to go through an object (with potentially multiple nested layers), an array or a string and replace any HTML special characters with the plain text equivalent.

At first I thought I would run a switch on the variable being passed in and then treat it differently for each type (object, string, array). This quickly fell apart when I thought about having to parse nested objects without knowing how many levels they might have.

So a solution struck me, why not convert it into a string, do the replacement, then change it back to the variable type it was before. Enter JSON methods…

If you JSON.stringify any variable you can then convert it back to its initial state once you have completed any operations on it with JSON.parse. With that in mind here is my html special characters function.

This post has been viewed 2318 times.

One thought on “String replace in objects and arrays in Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *