Javascript function that converts unicode notation code to utf-8 in HTML - javascript

I follow the link How to convert javascript unicode notation code to utf-8? to run the function in my console.
function encode_utf8( s ){return unescape( encodeURIComponent( s ) );}( '\u4e0a\u6d77' )
Then I get:
"上海"
However, when I do this way:
foo = function(s){return unescape( encodeURIComponent( s ) );}
foo('\u4e0a\u6d77');
foo("\u4e0a\u6d77");
Then I get"ä¸æµ·" "ä¸æµ·"
What is wrong with the function? Thanks ahead.
EDIT:
I thank you guys' explanation. Now I find that you just need to directly input in Chrome console '\u4e0a\u6d77', then I will get "上海".
However my original problem is that I want to convert unicode code to utf-8 in the html file, not in console. I could not find the answer.
EDIT:
Again, I want to thank you guys.
Now I find that my problem is that I get string like '\\u4e0a\\u6d77' from txt file. (Note here there are two back slashes). How can I change it to '\u4e0a\u6d77' (I want to get rid of one back slash).
Now I know once you get '\u4e0a\u6d77' (only one back slash) and then HTML will automatically show it as "上海"
EDIT:
Now I find the solution: HERE

Your first one is a function declaration followed by an unrelated expression in parentheses containing a string literals. The function is never called. The end result of that in the console is the value of the expression within the parens, which is the value of the string '\u4e0a\u6d77', which is of course "上海".
Your second one first creates the function (via a function expression), then calls it (twice, for some reason), passing in that string, and shows the function's return value.
So you see a difference because in the first case, you never call the function, you just get back the same string you provided. In the second case, you actually call the function and get back the UTF-8 data.

Related

Difference between eval() and eval`` (with backticks)

So I have came across a curious question that I can't find its answer anywhere and there isn't much documentation on what eval does when you pass to it string literals.
If I do eval("alert(1)") I will get an alert box with 1, however, when I do eval`alert(1)` I just get an array with "alert(1)" I am not sure where that is coming from, isn't it supposed to be treated the same as the previous example?
Also, eval`${1}` returns an array with two empty elements, why?
What you're running into is something to do with tagged templates.
Essentially, you are doing string interpolation and using a function to decide how to create the string. The first argument is expected to be an Array that contains all of the string parts (everything between ${var} declarations). The return of any function used this way is expected to be the string. The reason you are seeing 2 entries is because this function returns a raw format in addition to the one it tried to create using the tag function.

Jmeter: Javascript variable not returning any value

I am using one Javascript function to generate a random Number.
Used a User Parameter(Preprocessor) under the request
Added a Variable: farmeid
Function: ${__javaScript('bam-'+parseInt((Math.random()*1000000),10))}
When I am using the varialble ${frameid}, it is returning no Value.
The problem is that there is a comma in your expression here: ),10 which acts as a delimiter for function parameters. If you can remove this ,10 bit so your expression could look like:
${__javaScript('bam-'+parseInt(Math.random()*1000000),)}
This would be successfully evaluated by __javaScript function.
If this 10 bit is a must you can use BSF PreProcessor with the following code:
vars.put("frameid",'bam-'+parseInt((Math.random()*1000000),10));
And the easiest way is using __Random function like
bam-${__Random(111111,999999,)}
directly where it's required.
Hope this helps.
It's better to use Jmeter's Random Variable generator.
http://jmeter.apache.org/usermanual/component_reference.html#Random_Variable
Cheers,

How to execute a Javascript function in python with selenium

I have a function called 'checkdata(code)' in javascript, which, as you can see, takes an argument called 'code' to run and returns a 15-char string.
So, I found out (and tested) how to call no-argument functions in javascript, but my problem is that when I call checkdata(code), I always get a 'none' return value.
This is what I'm doing so far:
wd = webdriver.Firefox()
wd.get('My Webpage')
a = wd.execute_script("return checkdata()", code) //Code is a local variable
//from my python script
print a
I'm making this, since I read it on an unofficial selenium documentation and here: link
But, as I said before, I just keep getting none printed.
How can I call my function passing that parameter?
Build the string
a = wd.execute_script("return checkdata('" + code + "');")
Rather than building a string (which means you'd have to escape your quotes properly), try this:
a = wd.execute_script("return checkdata(arguments[0])", code)

Max length for a function parameter

Is there any max length for a JavaScript function() parameter?
I created a function which had a long parameter, but it didn't work. When I shortened the parameter of the same function, it worked. Does that mean that there is a maximum length for a function argument? If so, please recommend alternatives to my current method.
JavaScript
function example(idnum) {
alert(idnum);
}
HTML
<div onclick='example(*php variable,no special character included*)'></div>
When the PHP variable is long, such as "17b6f557969619544eb1e6cd58c3f341", it does not work. But if I change the variable to something like "203", the function works successfully.
"Douglas Crockford" wrote in message
news:9a027$3fa7c56d$44a4aebc$9152#msgid.meganewsse rvers.com...
[color=blue]
... . The maximum length with will be implementation-specific. ...[/color]
In microsoft.public.scripting.jscript, Michael Harris
(Microsoft.MVP.Scripting), who might be expected to know, quoted:-
In JScript,
variant string variables have the same limit as in VBScript, up to
2^31 characters.
String literals (as in "this is a literal") have (IIRC) a limit
~2^10 (1024) characters.
for the JScript implementation.
Blockquote
Sounds like you actually want to pass the PHP variable's value literally to the function, not as a variable name.
example(17b6f557969619544eb1e6cd58c3f341)
tries to call the function with that variable (likely causing an exception, or even being a syntax error), while
example(203)
calls the function with the number literal for the integer 203. If you want to pass the value as a string, use json_encode!
Also notice that you will need to escape everything for use in a HTML attribute (i.e. escape quotes, < and >), as you have
<div onclick=" [some code here] ">

Evaluate the string as object (javascript)

Here is the problem string:
$.ajax(......
,success:function(msg){
var obj = eval('['+msg.d+']');
},
....
}
msg.d contains something like:
new Person(2, 'Name Surname','This is just string came from Par'is at Sat'urday');
How can pass the javascript problem ?
If the string really is as you've quoted it, it has a syntax error and will not work (it has an errant ' inside the word "Saturday"). Otherwise, though, change the brackets ([ and ]) in your eval call to parentheses (( and )):
var obj = eval('('+msg.d+')');
However, it should almost never actually be necessary to do this (or indeed to use eval at all). It's almost always possible, and desirable, to refactor slightly and avoid it.
If that's a literal quote from your code, see also dvhh's answer below, your function argument name (msg.d) is invalid.
Using eval in this scenario is actual quite dangerous. You really ought to be using XML or JSON. (That's why they call it AJAX.)
the function argument should be a valid javascript identifier
try changing msg.d to msg_d for example
You may need to escape your string, because this example works fine:
function MyObject(myvar){
this.hello = function(){
alert('myvar= ' + myvar);
};
}
var obj1 = new MyObject('hello');
obj1.hello();
var obj2 = eval("new MyObject('world')");
obj2.hello();
(Edit: By the way, I assume msg.d is a typo due to editing the snipplet before posting on StackOverflow ?)
I would avoid using eval() for security reasons. If a user can get malicious code into the database, there's a chance it could end up in this eval expression, wreaking havoc for anybody who visits this page.
Instead of using eval, I'd recommending returning JSON from the AJAX request. You can then easily parse the values and build a new Person object with that data.

Categories