I need to use Java to replace some JavaScript in a file. The steps I'm taking are basically like this:
- Read in a file (it's an .asp file with JavaScript in it that is generated from another system)
- Replace the unwanted JavaScript function with one I do want
- Write it back out over the file that was originally generated
I'm having trouble with step 2 because my code seems to freak out on the replaceAll method. Let's say I want to replace this method:
function sayHi() {
alert('hi');
}
...with something like this:
function sayHi() {
alert("Hello, World!");
}
I have code that looks like this:
private static final String REPLACEMENT_METHOD =
"function sayHi() {\n" +
" alert('Hello, World!');\n" +
"}";
private static final String METHOD_TO_REPLACE =
"function sayHi() {\n" +
" alert('hi');\n" +
"}";
String content = // Get the contents from the file...
content = content.replaceAll(METHOD_TO_REPLACE, REPLACEMENT_METHOD);
The problem I'm running into is that the string that I want to replace is being interpreted as a regex (it's just literal text, but it is, of course, interpreted as a regex) and it bails out on me. Unfortunately, I've not been able to find the correct syntax to escape the special characters properly and still get it to match the way I want.
Any ideas?
Thanks!