replace(/[.?+^$[\]\\(){}|-]/g, '\\$&');
But it doesn't work in Java. So I changed the code as follows.
replace(/[.?+^$[\\]\\\\(){}|-]/g, '\\\\$&');
It doesn't work when I change it. Please help me :(
In Java, replace does not take a regex in the constructor, for that you need replaceFirst.
But as you are using the /g flag in Javascript for all replacements, you can use replaceAll.
In Javascript, this part $& in the replacement points to the full match.
So you want to replace the full match (which is one of these characters [.?+^$[\]\\(){}|-]) prepended by a \
In Java you can use $0 instead to refer to the full match.
You can also escape the opening square bracket in the character class \\[
For example
System.out.println("{test?test^}".replaceAll("[.?+^$\\[\\]\\\\()\\{}|-]", "\\\\$0"));
See a Java demo
Output
\{test\?test\^\}
The same output in Javascript
console.log("{test?test^}".replace(/[.?+^$[\]\\(){}|-]/g, '\\$&'));
"[.?+^$[\\]\\\\(){}|-]". Also, if you want to replace all occurrences, you need to useString.replaceAll