I need to escape some special characters from a JS string, but I can only replace one or more occurrences with a single character.
For example, I want to replace & with & but when I escape this string: &&& I get &&&.
I’ve been using
input = input.replace(/&/g,"&");
I know that the solution to this problem probably has to do with using an anonymous function, however I also need to escape about 10 other characters. I can’t see a way to pass the replacement as a variable to the function. Does that mean I’ll have to write 11 separate functions?
Your code is okay, it seems that you have tested it without
/g.You can also use:
replace(/(&)/g,"$1amp;");See and test the code here.