I'm using JavaScript to set the value of an input with text that may contain HTML specific chars such a &
etc. So, I'm trying to find one regex that will match these values and replace them with the appropriate value ("&", " ") respectively, only I can't figure out the regex to do it.
Here's my attempt:
Make an object that contains the matches and reference to the replacement value:
var specialChars = {
" " : " ",
"&" : "&",
">" : ">",
"&lt;" : "<"
}
Then, I want to match my string
var stringToMatch = "This string has special chars &amp; and &nbsp;"
I tried something like
stringToMatch.replace(/(&nbsp;|&)/g,specialChars["$1"]);
but it doesn't work. I don't really understand how to capture the special tag and replace it. Any help is greatly appreciated.