Replace Unicode from each output of NodeJS - Code optimization - javascript

I am reading data from a serial port and with test case capturing the required output, then this output is sent to html
now while reading from serial port, there are few unicode charachters in the output.
I can remove them by using
.replace(/[^\x0000-\xFFFF]/g, "").trim();
there are approx 50 places where I need to use this replace and trim method, so I am trying to define a function, where I can pass the output to the function and it will give me clean output.
So I do not have to write .replace and .trim to every output.
here is what I tried till now.
This is the function I define to do the replace and trim.
function cleanoutput () {
var output = output.replace(/[^\x0000-\xFFFF]/g, "").trim();
}
This is the function calling to the output
display.adults = cleanoutput (adults.slice(28, 31));
By doing this I am getting error in function cleanoutput
error - "Cannot read property 'replace' of undefined"
I am just learning nodejs, need help on making this work.

There are two problems with your function: first, you are using replace on a variable that probably is not defined yet but is probably intended to work on a parameter, that is not defined either.
The second problem is that your function is not returning anything, so it is implicitly returning undefined.
display.adults will be undefined after the execution of the cleanoutput function.
You can fix those problems with something like this:
function cleanoutput (output) {
return output.replace(/[^\x0000-\xFFFF]/g, "").trim();
}
My suggestion is to dive a little bit deeper into javascript functions.
There are plenty of articles, blog posts, and youtube videos on the topic and I'm sure you will find a good one.

Related

Variable not seen as string using getCurrentUrl in protractor

My goal is to store the current URL from one test case on a global variable and use it to access the URL from another test case
My global variable:
let loan_id;
After searching a bit on the internet I've found out that getCurrentlUrl doesn't return a string, it returns a promise, not know what that is i investigated a bit further and found out how to solve it.
loan_id = browser.getCurrentUrl();
loan_id.then(ln_id => {
console.log(ln_id);
This is one of my tried fixes, but in the end i get the same error:
Failed: The "url" argument must be of type string. Received an instance of ManagedPromise
Please explain to me why does the variable still behave as a promise after i tried to deal with it in the code above. I've tried all the posibilities which i've found on the web, including toString() but no luck...
browser.getCurrentUrl().then(ln_id=> {
loan_id= ln_id;
});
This is the correct way that worked for me

Javascript function expression use cases

I have been recently reading function expression and declaration in javascript and have referred to quite a few online articles about this. I also have seen quite a few discussion about this topic on SO. In the process of learning I tasked myself with a challenge, which I am not able to clearly explain.
Can I kindly request SO experts to help me gain some insight here?
Here is the problem scenario -
Scenario 1:
>var multFunc=function(n){var a=2; return n*a;}
>multFunc(6)
12
I understand this scenario and the result is what I was expecting (12).
Scenario 2:
>var multFunc1=function(n){return function(n){n*2}}
>multFunc1(6)
function (n){n*2}
I did not understand the second case. Why would it not return 12?
Can someone please help me understand this?
I have checked this link - Javascript Function Expressions, this link JavaScript Nested function
and I also did ask a similar question yesterday, but I guess I did not fully grasp the concept (as explained graciously by T.J) -
Trying a closure the wrong way?
The code:
var multFunc1=function(n){return function(n){n*2}}
returns a function. So multFunc1 represents the returned function, in this case:
function(n){n*2}
so you had to call like:
multFunc1(1)(2)
So basically the returned function remembers the value of n (passed argument, I recommend you to read about closures). So we can re-write the calls like:
var multFunc1=function(n){return function(x){n*x}}
var multBy2 = multFunc1(2)
var multBy16 = multFunc1(16)
multBy2(4) // 8
multBy16(2) // 32
Side note: The multFunc1's inner function, doesn't have any return statement, so it always returns undefined as #nnnnnn pointed out in comments
What you are essentially doing here in the second scenario is returning the function Object. Rather than returning the result of the execution of the function (which would be usually be 12) you are just returning the Reference to that object.
UPDATE:
I think you are missing the return statement inside the second function. By adding so, this yeilds the result I believe you are looking for.
var multFunc1=function(n){
return function(n){ return n*2}
}
// The first set of () require no argument as
// they are never used withing the second function.
multFunc1()(6);

Javascript error halts $document.ready()

I'm updating an existing website running on Expression Engine. So far, I've stayed away from any code I didn't write or couldn't understand. I recently must have altered some bit of code someplace (helpful, I know) and now a block of JS I didn't write is causing an error that seems to bypass the document.ready() event. The window.load() event however is still taking place.
In the Chrome DevTools Console, the error "Uncought TypeError: Cannot call method 'replace' of UNDEFINED" points to the definition of a function "fixedEncodeURIComponent" pasted below.
$("#MessageContainer.Counted").counter({
type: 'char',
goal: 250,
count: 'down'
}).change(function(){
var TEMP = fixedEncodeURIComponent($(this).val());
$("#Message").val(TEMP);
});
var TEMP = fixedEncodeURIComponent($("#MessageContainer.Test").val());
$("#Message").val(TEMP);
function fixedEncodeURIComponent (str) {
str=str.replace(/"/g, '');
return encodeURIComponent(str).replace(/[!'()*]/g, escape);
}
As I interpret the error, this function is being passed a variable that is not a string. I added an alert(str) to the function definition and the result was UNDEFINED as I expected. The first of several unknowns for me is which call to the function 'fixedEncodeURIComponent' is being passed a bad variable. I assume that it's the first call, but that's just a guess. It so happens that this first call contains a syntax I have never encountered before. I don't know how to interpret what happens when $(this) is passed as a function argument.
Any insights would be greatly appreciated. Also, if there's more information you need please let me know. The client's site is password protected but I can include any code you request.
Thank you.
I'm taking a guess that the }); on line 3 is exiting a document.ready context. If that's the case then your second call to fixedEncodeURIComponent may be getting called before the DOM is even loaded.
Start by wrapping
var TEMP = fixedEncodeURIComponent($("#MessageContainer.Test").val());
$("#Message").val(TEMP);
in a
$(function() {
// code
});
block. If that doesn't work, check that #MessageContainer.Test actually matches an element. Since this is code you inherited, the class name "Test" clues me in that the block in question might be a remnant of someone trying to debug an issue and maybe it should have been removed.
I suspect $("#MessageContainer.Test") since it looks like its supposed to be an ID selector instead of what it actually is when jQUery parses it(which is an ID selector combined with a class selector). $("MessageContainer\\.Test") allows you to select an element with ID MessageContainer.Test

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)

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