I have a list of special characters:
+ - & | ! ( ) { } [ ] ^ ~ * ? \ :
I want to escape all of them with a leading \\
except of \
that needs only ohne leading backslash \
e.g. a string that is (1+1)\2
must be changed to \\(1\\+1\\)\\2
In fact it prepends two backslashes to each defined special character, and only one backslash to a backslash.
I wrote this function, that works actually quite good:
function escapeSpecialCharacters(input) {
var output = input.replace(/\+/g, "\\\+")
.replace(/\-/g, "\\\-")
.replace(/\&/g, "\\\&")
.replace(/\|/g, "\\\|")
.replace(/\!/g, "\\\!")
.replace(/\(/g, "\\\(")
.replace(/\)/g, "\\\)")
.replace(/\{/g, "\\\{")
.replace(/\}/g, "\\\}")
.replace(/\[/g, "\\\[")
.replace(/\]/g, "\\\]")
.replace(/\^/g, "\\\^")
.replace(/\~/g, "\\\~")
.replace(/\*/g, "\\\*")
.replace(/\?/g, "\\\?")
.replace(/\:/g, "\\\:")
.replace(/\\/g, "\\\\");
return output;
}
console.log(escapeSpecialCharacters("(1+1)\\2"));
But im not happy with the current implementation. Because i think its quite hard to read an to maintain.
Is there any other "smarter" solution/framework available for this problem? I was thinking of a function that uses a given list of special characters to replace them in my string.