Zapier Javascript Find/Replace Special Characters - javascript

I am passing order data from Shopify to VimeoOTT using Zapier. We have been doing this for a year and it works great, except when the customer's name has special characters in it. For example "Jack & Jill (tumble)" The & or ( parenthesis ) causes an error that stops the process.
I am trying to use Zapier's Javascript Action to find and replace the name data's special characters, but I keep getting a coding error. This is my first time working with Javascript :(.
This image shows the Zapier Code Action
Here is an image showing the error I get
// this is wrapped in an `async` function
// you can use await throughout the function
nameFix = inputData.nameFix.replace(/[^a-zA-Z0-9 ]/g,'_').replace(/_{2,}/g,'_');
output = [nameFix];

In javascript, variables must be declared before they are used using let or const:
const nameFix = inputData.nameFix.replace(...
So, that'll fix the error you're seeing.
Separately, JS steps in Zapier must return an object (which has keys and values). So, you'll want to return the result like so:
return {result: nameFix}

Related

Creating custom spell checking for html

Is it possible to use some custom functions for spell checking in html inputs? For example I have an input where values are divided by spaces (or commas, doesn't matter) and a function which receives tokens from it. That function decides if token is spelled correctly (in my case there would be some regular expression) and returns true/false value and based on that some words would be underlined. In my head it looks something like this:
<input type="text" onCheck="checkToken">
<script>
function checkToken(token) {
const oneCrazyRegex = /[a-b]/;
return oneCrazyRegex.test(token);
</script>
Or taking whole input:
function spellCheckInput(line) {
// line is an array of tokens
return line.map(tok => checkToken(tok));
}
Is it possible to do with js/css/html or not?
P.S. onCheck is example only, I know that this attribute is not valid
Yeah you can use regex for cleaning up text but you have to remember that people can fabricate any kind of input they want since the checks would be happening client-side, and anyone can just pop open a console and send anything they want.

Blockly: type check of child blocks during code generation

I am trying to generate code from blocks that can have any input type to JavaScript. But to do so I need to know what type these blocks are during generation time.
Most blocks already have a type internally for the type check
"output": ["Integer","Number"],
or
this.setOutput(true, 'String');
but I can't find a function to access the 'output' field with.
Ideally I want to access the type in the generator function like this:
var return_type = block.getChildren()[0].functionToAccessOutputWith;
There is the '.type' field but that one gives the name of the block type not the return value defined with output.
It seems like a very common problem but I can't find anything online.
Just trace through the source code by following the function calls of Block.setOutput(). It's not that hard. Eventually you will reach a line in Blockly.Connection that says this.check_ = check;
So what you are looking for is basically block.outputConnection.check_. But this is not a function and the _ indicates that it is supposed to be a private property. For convenience I'd write a getter function into Block.

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:
var UserName = #Request.QueryString["UserName"];
But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:
var UserName = ANT -- ANT 37690 / THIRD PARTY
So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS?
The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].
One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.
var UserName = #new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);
The shorter version of this for a string is:
var UserName = "#System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";
or overloaded version that wraps the result in double quotes:
var UserName = #System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);
You need to include quotes for the value.
var UserName = "#(Request.QueryString["UserName"])";
Otherwise the name will come through verbatim in your code and cause the problems you are seeing.
There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.
If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.
var sanitizedJsVariable = "#System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

Illegal Character error in jQuery - regardless of function content

First of all, I've done my research and I did find a bunch of simialr questions. However, I didn't find an answer that applies to my problem. All the examples I found were related to unescaped characters, single/double quote mishaps and the like. I on the other hand am getting this error on the following function:
$('.seq_input').blur(function(){
//var id = $(this).data('id');
//var index = parseInt($(this).val()),
//element = $("#test-list li").eq(id).remove();
//$("#test-list li").eq(index - 1).before(element); // -1 because users like 1 based indices
alert('what?');
})​​​;
As you see I commented out everything and just left an alert, and I'm still getting the error, pointing to the last line of the function. It couldn't have anything to do with other functions because I just added this one alone at the end of my current Javascript.
Can someone please tell me what's going on here? Why on Earth would a function that just alerts something (or even if it doesn't do anything) give an error?
NOTE: error is shown as soon as the page is loaded
There are invisible characters between the trailing semicolon and the parenthesis. I concatenated your code, put it in a string, and called a non-existent function in order to trigger a error (using this method).
'})​​​;'.l()
>>> TypeError: "})\u200B\u200B\u200B;".l is not a function
$('.seq_input') may used on the other functions, try using new id to do that function.

In JMeter and BeanShell, how can I make a variable lowercase?

In JMeter's User Parameters, how can I make a variable lowercase?
Left column
my_lowercase_variable
Right column
${__BeanShell('${my_variable}'.toLowerCase())} //fails
or
${__javaScript('${my_variable}'.toLowerCase())} //fails
Such that ${my_lowercase_variable} is lowercase of ${my_variable}. Tried with quote and without and escaping and such. No luck. Any tricks or tips welcome.
Note to self.
It turns out to be a two liner in BeanShell Sampler rather than a __BeanShell command. Not exactly in the examples unfortunately.
I added the BeanShell Sampler under the Thread Group, then made a variable. No parameters in the form were required only the two liner script below. As long as I don't change the variable I can copy the data to another variable, change that instead, and then make a Value reference to that wherever needed.
First define a variable in some User Parameters or such
ie:
Name: my_initial_reference
Value: ITS IN CAPS
Add a Bean Sampler under the User Preferences or definition list (just next, it's not a child process)
Put in:
String blah = "${my_initial_reference}"; //
vars.put("blah", blah.toLowerCase()); //${blah} = "its in caps" now available
Now under that with Name/Value pairs I can map ${blah} as the value to whatever process name requires it.
Note that the Debug response will still show the initial value in caps but you'll also see blah=its in caps which is what I wanted to use.
Simply can add a function
${__lowercase(${VAL},VALUE)}
${__uppercase(${VAL},VALUE)}
Note: VAL can be correlated or paramiterized value (e.r VAL= TO LOWER or VAL= TO UPPER). We can use this function in beanshell (pre-processor/post-processor/sampler). Jmeter version using (2.6).
Can use it where ever we want in the script as ${VALUE}.
${__javaScript('${foobar}'.toLowerCase())} does work. If the output is ${foobar} instead of desired value, it means that the variable has not been declared
Note that variables are defined only after the "User Defined Variable" component has been parsed. Variables cannot be reused within a single "User Defined Variable" component e.g.:
The second row in that image will not be able to refer to the variable my_variable in the first row. To be able to refer to the first variable, two "User Defined Variable" components is needed. The first variable will be in the first component and the second variable in the second one, e.g.:
With that, ${my_lower_case_variable} will successfully be converted into some value.
${__BeanShell("${my_variable}".toLowerCase())} works too. (Note that Bean Shell requires double quotes. The code in your question uses single quotes.)
Another way is to use vars.get:
${__javaScript(vars.get('my_variable').toLowerCase())}
${__BeanShell(vars.get("my_variable").toLowerCase())}
Hmmmm, your bean shell code didn't work for me. The bean shell sampler returned:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String blah = AAP; vars.put("blah", blah.toLowerCase()); //${blah} now availab . . . '' : Typed variable declaration : Void initializer
I added two double quotes to solve it:
String blah = "${my_initial_reference}";
vars.put("blah", blah.toLowerCase()); //${blah} now available
The beanshell and JavaScript functions in this use will fail, because they don't import the packages you need in order to use .toLowerCase.
If you really need to use a function to convert case (rather then declaring them as lowercase in the first place), you may need to write a full beanshell post-processor script in order to import the needed packages.
http://jmeter.apache.org/usermanual/functions.html#__BeanShell
http://jmeter.apache.org/usermanual/functions.html#__javaScript
http://www.javadocexamples.com/java_examples/org/apache/jmeter/
var blah = "${my_initial_reference}";
blah.toLowerCase();

Categories

Resources