Today I hit a snag when I wanted to use a variable in Javascript’s replace function. Of course Javascript isn’t as easy as PHP as in order to replace content from a string or variable it has to be a regular expression. Luckily there is an easy enough way to convert your variable into a regular expression perfect for sending through the javascript replace function.
The Solution
Use javascripts RegExp to convert your variable before parsing it through the replace function.
var regex = new RegExp(yourvariable, āgā);
return yourstring.replace(regex, āreplacedā);
It’s quite an easy solution, no major hair pulling involved!




