Example of how to use PEG.js - javascript

I'm playing around with PEG.js.
I created some simple code that accepts inputs in the form [LettersNumbers]:
abc123
hello98765
etc.
This is the code:
start = expression
expression = text + number
text =
a: [a-z]+
{return a.join("");}
number =
b:[0-9]+
{return b.join("");}
Here: Online version the code can be tested and the parser downloaded, additionally I downloaded peg.js itself.
Unfortunately, the documentation is very sparse. I tried:
<script src="peg-0.9.0.min.js"></script>
<script src="parser.js"></script>
<script>
var parser = new PEG;
parser.parse("test123");
</script>
But got these errors:
Uncaught ReferenceError: module is not defined
Uncaught TypeError: PEG is not a function
Could anybody please provide me with a working example? I just need to integrate the generated js-files into a website.

This answer assumes that you would like to continue using the PEG.js online version to build your parser.
You only need peg-0.9.0.min.js if you are generating the parser in your web page. Since you are using the PEG.js online version to generate your parser you don't need to do that.
You do need to include the downloaded parser.js. You need to specify a browser-friendly global variable in the PEG.js web version and re-download.
This example uses PARSER:
Following that you can use:
<script src="parser.js"></script>
<script>
PARSER.parse("test123");
</script>
Plunker example

If you want to use it on web, you need to download the browser version, or ref it from CDN.
Also, you need to use its javascriptAPI to create a parser.
// One line version of your grammer.
var parser = PEG.buildParser('start = expression;expression = text + number;text = a: [a-z]+{return a.join("");};number = b:[0-9]+{return b.join("");}');
console.log(parser.parse("test123"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/pegjs/0.7.0/peg.min.js"></script>

Related

Convert a javascript variable to scala in play framework

I have some variables in javascript:
var something = 1;
var url = "#CSRF(routes.Some.thing(something))";
I get an error during compilation because "something" does not refer to the javascript variable, in other words; the compiler can't identify it. Is it possible to convert/inject the javascript variable somehow? Also, does this work in real time in javascript or do I need to prepare an "#CSRF(routes.Some.thing(something))" array containing each possible "something" value?
It's supposed to be a simple rest call, seen in routes file:
/something/:something controllers.Some.thing(something : Long)
An alternative would be to use a form, but I want to try not to.
You need to use a Javascript Routing and add the CSRF token to the request.
Javascript Rounting description: https://www.playframework.com/documentation/2.6.x/ScalaJavascriptRouting
Look at my answer to the question with explanation how to use it for assets("Correct and long solution"), the usage for other activities is the same: How to update src of a img from javascript in a play framework project?
So in your case, the Javascript routes generation can look like:
JavaScriptReverseRouter("jsRoutes")(
routes.javascript.Some.thing
)
And in the JavaScript:
var something = 1;
var url = jsRoutes.controllers.Some.thing(something).url;
The last - do not forget to add Csrf-Token header to the request.

Why declaring a simple JSON object into a JavaScript script executed into Rhino is not working?

I am not so into JavaScript. I am using JavaScript to develop a litle script working on a JSON document. This JavaScript script is not executed into the browser but ino another product that allow to use JavaScript to script some tasks (the prodcut is WSO2 ESB but it is not important at this time).
This product (WSO2 ESB) uses Rhino as JavaScript engine, used to implement JavaScript scripts into Java application.
I have some problem trying to create a simple JSON object in this kind of environment.
I have done something like this (into my WSO2 ESB code):
<script language="js">
<![CDATA[
var response = JSON.parse(`
{
"forecast": []
}
`);
]]>
</script>
Using the same code into a classic JavaScript file performed into the broswer it works fine but it seems that it can't work using Rhino. I obtain error relating an illegal character (I also tryied to replace the ` and ` with " and " and with ' and ' but I still obtain error).
Something like this in the Java Stacktrace:
Caused by: javax.script.ScriptException: org.mozilla.javascript.EvaluatorException: illegal character (<Unknown Source>#9)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:341)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:323)
at org.apache.synapse.mediators.bsf.ScriptMediator.initInlineScript(ScriptMediator.java:399)
... 32 more
What could be the problem with Rhino? I think that the problem could be related to the `` character that maybe have to be escaped in some way. Some idea?
Or another something more pure JavaScript workaround solution could be: is it possible declare a JSON object like this:
{
"forecast": []
}
in a different way? I mean in a programmatically way without explicitly declare it.
This works in modern browsers that support ES6 with template literals:
var response = JSON.parse(`{"forecast": []}`);
Why, because JavaScript solves the back ticks first as a template and fills them with the content of the variables before the JSON string is parsed:
var test = "Cloudy";
var string = `{\"forecast": ["${test}"]}`;
var response = JSON.parse(string);
console.log(response);
But maybe your Rhino build has no ES6 support, so that won't work. Also the multiline is causing problems:
var response = JSON.parse(''+
'{'+
' "forecast": []'+
'}'
);
console.log(response);

_str is not defined while using underscore.js

This is the first time I am using Underscore.js. I have included the production underscore-min.js at the bottom of my page ( which is in Jade originally ), just before my custom script.
<script src="/javascripts/underscore-min.js">
<script src="/javascripts/custom.js">
Now, I call this function in my custom.js:
var selections = "Bold;Business-like;Charming";
var num_selections = _str.words( question.selected_words, ";").length;
Basically, I need to know the number of words selected and the native javascript method split returns 1 for even a blank string. But when I use this code, I get this error in my browser console:
Uncaught ReferenceError: _str is not defined
I tried using this line before using _str, but then I get require is not defined:
var _ = require('underscore');
Or, perhaps I can put my question as How do we start using underscore functions in our front-end javascripts?
Even though you are using node, require is not available on the front-end. Front-end javascript is not the same as back-end, nor do they directly interact. Underscore is called using _. All the methods available here: http://underscorejs.org/ are accessed via _.<method_name>. I am not too familiar with underscore and maybe you are using an older version but I cannot find _.str anywhere in the docs. So first, make sure you are using the correct notation for underscore _.<method_name> and make sure the function exists in the documentation. This fiddle shows some basic underscore functions: https://jsfiddle.net/mawpw2c5/

Why use JSON.parse(decodeURIComponent(staticString))?

Certain dynamic web frameworks use this code fragment
<script>
appSettings = JSON.parse(
decodeURIComponent(
"%7B%22setting1%22%3A%22foo%22%2C%22setting2%22%3A123%7D"));
</script>
Is there a standard HTML5/JavaScript problem are they trying to solve with this code. Why not just
<script>
appSettings = {"setting1":"foo","setting2":123};
</script>
Note: this is dynamically generated code. I'm assuming on the server they are doing something like
var settingsString = encodeURIComponent(JSON.stringify(settings));
var output = '<script>appSettings=JSON.parse(decodeURIComponent("' +
settingsString +
'"));</script>';
But it seems like it would work just as well like this
var settingsString = JSON.stringify(settings);
var output = '<script>appSettings=' +
settingsString +
';</script>';
One idea is the latter could contain code but they are the ones providing the string, it's not user data so they're no chance it could be code. Plus using JSON.stringify on the server would remove all code. On the client even then a simple JSON.parse of a JSON.stringifyied object would prevent code.
Is there a concrete problem being solved by the triple parsing? Once by JavaScript, once by decodeURIComponent, once by JSON.parse?
THIS IS NOT AN OPINION BASED QUESTION
The question is what problem is being solved. Either there is a problem being solved or there is not. No opinions required to answer that question. For example if JSON.stringify happens to emit unparseable code sometimes (which as far I know it doesn't but if someone knows better then that would be a good answer as to why).
Also note: I'm not asking why their framework does this. I'm asking if there is real problem being solved in standard HTML5/JavaScript. In other words, should I adopt this pattern because I'm going to run into an issue someday if I don't.
Is there a concrete problem being solved by the triple parsing?
Yes. Your suggested solution has two problems:
It's parsed as HTML. Things like </script> can cause havoc in an inline script.
It's parsed as JS. Not all JSON strings are valid JS literals.
The decodeURIComponent + JSON.parse approach is a crude workaround however and looks more like a quick fix than a proper solution.
#katspaugh is correct
Testing
var settingString = JSON.stringify({
"</script>": "<script>bar=123</script>",
});
Generates the code for the above example as
<script>
appSettings = {"</script>":"<script>window.bar=123</script>"}
</script>
Which fails to parse as HTML. Adding the encodeURIComponent on the server JSON.parse(decodeURIComponent(...)) on the client fixes that issue
DO NOT USE IT.
let str = `C:\\Users\\Administrator\\Desktop\\小灶\\GT4T_translated_Chinese Simplified (简体中文)\\2013\%2F193461.pdf`
let newStr = decodeURIComponent(JSON.parse(`"${str}"`))
Depending on the str content, you may get unexpected errors. The code above will cause this error:
SyntaxError: Unexpected token U in JSON at position 4

How to include more JavaScript inside Atom editor by Github?

I've been playing with snippets for Atom editor,
and see that I've learned I can include
JavaScript inside of a snippet, as my example shows.
(It inserts a TODO Comment with date)
TODO: (RAM) Fix this - 2014-11-23 20:55
HELLO
How can I include MORE JavaScript.?
For example
inside the snippet to set
var= to something
or
call a JS library
or
ask for input from user i.e. confirm();
and proceed on basis of confirm() function.
Any help would be appreciated, I looked for a long time,
but not much documentation on this. Submlime Text's snippets allowed lots of code to be inserted via Python.
Thanks
~Rob
Inside file snippets.cson
'.source.js':
'Date TODO: insert':
'prefix': 'datetd'
'body': """
TODO: (RAM) $1 - #{datetime = new Date(); datetime.getFullYear()}-#{(datetime.getMonth()+1)}-#{datetime.getDate()} #{datetime.getHours()}:#{datetime.getMinutes()}
#{"hello".toUpperCase(); }
$2
"""
Update: With the merge of atom/atom#4791, the capability of putting CoffeeScript code in CSON configuration files has been removed from Atom. The rest of the answer has been left intact for historic reference.
Actually, the syntax of the file is CoffeeScript (hence .cson as in CoffeeScript Object Notation), not JavaScript. It just so happens that you typed in JavaScript that is allowed as CoffeeScript. CoffeeScript doesn't use the var keyword, so you can assign variables like you did in your example:
datetime = new Date()
The other items, you'll probably have to get a little creative. I don't believe that the snippets package was intended to be used in this manner, which is why the lack of documentation on the "feature".

Categories

Resources