Using variables in Javascript.replace - javascript

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?

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

Related

JSON Parse causing 'undefined' json values - Javascript

I have searched far and wide for answers to my problem but I am just not winning, I am hoping someone will be kind enough to offer me some guidance.
My below Javascript code is returning undefined json values:
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}'
var stringified = JSON.stringify(req);
console.log('stringified json ' + stringified);
//json = JSON.parse(JSON.stringify(stringified))
var json = JSON.parse(stringified );
console.log('parsed json ' + json);
//testing different ways of pulling out the data, all undefined
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json[testValue];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
The complication comes in with the backslash in the testValue property.
If I do not stringify the json first, I receive the following error:
SyntaxError: Unexpected token P in JSON at position 143
As soon as I Stringify however, and then parse, the values come back as undefined.
Does anybody perhaps know what I am doing wrong please?
Thanks
If you know that your data will never properly escape backslashes, a quick solution is the following:
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
JSON.parse(req_escaped)
Basically, make your string JSON compliant and then use the usual parsed method.
replacing the backslashes compiles. also you need to add " around testValue when you get it from the json
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}';
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
var json = JSON.parse(req_escaped);
console.log(json);
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json["testValue"];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
If you have control over the escaping process, the backslashes path should be escaped as follows:
\\ should be \\\\
The first escape escapes it in the Javascript string literal. The second escape escapes it in the JSON string literal. Credits and more details.
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\\\ProgramTest\\\\"}'
console.log(JSON.parse(req))

How extract some part of a javascript from a webpage using jsoup?

i want to extract some data from blow script
$(document).ready(function(){
$("#areaName").val(1);$("#state").val(29);$("#city").val(1);
$("#subareaName").val(1);$("#lane").val(1);
}
like areaName value = 1, state value = 29, city value = 1, subareaName value = 1, lane value = 1
How can i achieve this using jsoup?
Jsoup is html (xml) parser. You can use it to extract javascript from page source for example like this: Elements scripts = document.select("script");
Then you will have to parse the script by yourself. You can use regex to do so.
Here is an example.
final String propertyName = "areaName";
final String regex = "#" + propertyName + ".*?val\\((.*?)\\)";
final String script = "$(document).ready(function(){ \n"
+ " $(\"#areaName\").val(1);$(\"#state\").val(29);$(\"#city\").val(1);\n"
+ " $(\"#subareaName\").val(1);$(\"#lane\").val(1);\n"
+ "}";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(script);
if (matcher.find() && matcher.groupCount() > 0) {
String areaName = matcher.group(1);
System.out.println(propertyName + ": " + areaName);
}

How to correctly evaluate Javascript string containing JSON.parse expression with special characters?

I need to evaluate a JS expression created in the following way
function createExprs(obj){
var decl = "var i = ";
var value = JSON.stringify(obj);
var exprs = decl + "JSON.parse('" + value + "')";
return exprs;
}
var i = createExprs({1:2});//i = "var i = JSON.parse('{"1":4}')"
eval(i); // works fine
However it fails when the obj contains any special characters
var i = createExprs("today\\.article") \\i="var i = JSON.parse('"today\\.article"')"
eval(i) // Unexpected token . in JSON
You need to escape the ":
"var i = JSON.parse('\"today.article\"')"

How to add spaces in the first and the end of a string variable

I'm trying to add spaces in the first and the end of this string variable, I tried to convert the string to an array, then add space with push() and unshift() ... but it returns "x.push is not a function"
function space_fb(x){
x.split(" ");Array.prototype.slice.call
x.push (" ") ;
x.unShift (" ") ;
return x.join(" ");;
}
var xxx = "Medardo";
space_fb(xxx);
alert(xxx);
There is many ways this can be done you could simply add the spaces in your string value for example like " Medardo " and it will work, But My example would handle dynamic string data.
You dont need that space_fb function at all its dead simple:
var xxx = " " + "Medardo" + " ";
alert(xxx);
Edited as OP wanted it in a function as his "teacher wants him to"
function AddSpaces(x){
return " " + x + " ";
}
var xxx = AddSpaces("Medardo")
alert(xxx);
How about this? JSON.stringify ist just to show the output in this way.
var x = "foo";
function addSpaces(string){
var a = string.split("");
a.push(" ");
a.unshift(" ");
return a.join("");
}
document.write(JSON.stringify(addSpaces(x)));
This is because you are using method split but the variable is not being assign
you have two options
1.- x = x.split();
or
2.- var myArray = x.split(" ");
This is all you will need do not use the + + operators. A . is a concatenation operator.
var xxx = ' '.xxx.' ';
As mentioned by #itsgoingdown, in JavaScript you can append strings using the + operator. There is really no need to split the string into a character array and push/unshift to add spacing.
function space_fb(x){
x.split("");Array.prototype.slice.call
x.push (" ") ;
x.unShift(" ") ;
return x.join("");;
}
var xxx = "Medardo";
space_fb(xxx);
alert(xxx);

Javascript regex with variable

I have the following string in a variable named js:
some code here
/* start-rotateControlOptions */
some more code here
on multiple
lines
/* end-rotateControlOptions */
some code here
And I want to end up with:
some code here
some code here
Basically escape everything between these 2 specific comments.
The following works:
js = js.replace(/\/\* start-rotateControlOptions \*\/([\s\S]*)\/\* end-rotateControlOptions \*\//, '');
But now I need to have the rotateControlOptions as a variable.
This is what I have tried to no avail:
js = escapeCode(js, 'rotateControlOptions');
function escapeCode(js, identifier) {
var re = new RegExp("/\/\* start-" + identifier + " \*\/([\s\S]*)\/\* end-" + identifier + " \*\//");
js = js.replace(re, '');
return js;
}
What am I doing wrong? I get no error.
Escape all the backslahes one more time and you don't need to add the forward slash delimiter inside the RegExp constructor.
var re = new RegExp("/\\* start-" + identifier + " \\*/([\\s\\S]*)/\\* end-" + identifier + " \\*/");
Example:
> var str = 'some code here\n/* start-rotateControlOptions */\nsome more code here\non multiple\nlines\n/* end-rotateControlOptions */\nsome code here';
> var re = new RegExp("/\\* start-" + identifier + " \\*/([\\s\\S]*)/\\* end-" + identifier + " \\*/\\n");
undefined
> console.log(str.replace(re, ''))
some code here
some code here

Categories