0

I am trying to inject the replace method for javascript in webview for android.

This code works:

       {
            mWebView.loadUrl("javascript:(function(){" +
                    "document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');" +
                    "})()");
            }

Instead of putting the string in the method, however, I want to use variables. I tried using regex but it does not seem to work.

        {
            String old = "hello";
            String new = "hi";

            mWebView.loadUrl("javascript:(function(){" +
                    "var ol = new RegExp(old,'g');" +
                    "document.body.innerHTML = document.body.innerHTML.replace(ol, new);" +
                    "})()");
            }

Is there something off with my code?

3
  • So you want to evaluate that? Commented Mar 18, 2015 at 21:21
  • new RegExp(" + old + ",'g') and .replace(ol, " + new + "); Commented Mar 18, 2015 at 21:21
  • var doesnt seem to recognize the text inside as a string...any way to fix that? Commented Mar 19, 2015 at 0:01

1 Answer 1

2

You have to quote out the variables when passing them into a string like that

{
    String old  = "hello";
    String _new = "hi";

    mWebView.loadUrl("javascript:(function(){" +
                    "var ol = new RegExp("+old+",'g');" +
                    "document.body.innerHTML = " +            
                    "document.body.innerHTML.replace(ol, " +_new+ ");" +
                    "})()"
    );
}

Note that new is a reserved keyword, and shouldn't be used as a variable name

Sign up to request clarification or add additional context in comments.

1 Comment

sorry, i thought this would work and marked it as answer but it ended up not working when i put it in my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.