Is there a good math parser in Javascript? I want to be able to parse something like:
LOG(3.14)+5^2+POW(2,LN(X*2,Y))
Thanks,
Here is a brand new initiative:
http://mathjs.org
Comes with an extensive and easy to use parser which also supports assignment and usage of variables and functions like in your example expression.
Use this one. It defined an "operator" object that lets you define your own operators.
http://jsfromhell.com/classes/math-processor
Warning: it uses with. If you don't know why that's dangerous, find out before using this code in anything critical. Alternately, you could just re-write it without with.
Try nerdamer
var result = nerdamer('log(3.14)+5^2+2^(log(X*2)/log(Y))').evaluate();
document.getElementById('text').innerHTML = result.text();
<script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<div id="text"></div>
I know it's an old question, but I found it by chance and I have something to help. Not as complete as mathjs, but useful and fast.
Related
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
I know this is a super easy question, but I can't seem to wrap my head about it. I've got a bunch of URLs in varying languages such as:
www.myurl.com?lang=spa
www.myurl.com?lang=deu
www.myurl.com?lang=por
I need to create buttons to quickly switch from any language extension (spa, por, deu, rus, ukr, etc) to another language. I have the following code so far:
var url = window.location.toString();
window.location = url.replace(/lang=xxx/, 'lang=deu');
I just can't figure out the 3-character wildcard character. I know that I need to do some sort of regular expression or something, I'm just not sure how to go about it. Any help?
Thanks in advance
You can use
([&?]lang=)\w+
This will work with urls like www.myurl.com?foo=bar&lang=por&bar=foo too.
Instead of lang=deu, you'll have to replace with $1deu.
Try ... or .{3} or \w{3} or even [a-z]{3}, depending on how specific you want to be.
var s = 'www.myurl.com?lang=spa';
s.replace(/lang=[a-z]{3}/, 'lang=deu');
// => "www.myurl.com?lang=deu"
Here's a railroad diagram of the above example:
Use /lang=[a-z][3}/, here's an example:
/lang=[a-z]{3}/
Debuggex Demo
This may seem like a silly question to some. The short background is; I am clinically diagnosed with OCD, I am thus very particular about the formatting and neatness of my code so I apologize in advance. This leads me to my question:
Is there a way in javascript to instantiate an object and define its attributes in a block? My goal might be somewhat analogous to how you'd see a JSON object/string
Here's some pseudocode/formatting:
var preElement = document.createElement('pre')
.className = "nodeResults";
.innerHTML = formattedResponse;
.style = "blahblah";
.anymoreAttributes = "stuff";
Inconsequential, I know. I just noticed I spent 30 minutes researching this instead of writing functional code. Downfall of OCD. SO please help me; Is this possible yes, or no?
Sincerely,
WastingTehTime
This is not doable unless you write a class wrapper to handle this kind of formatting, or use the jQuery library.
jQuery example:
var preElement = $(document.createElement('pre'))
.addClass("nodeResult")
.html(formattedResponse)
.css(jsonFormattedCSS)
jsFiddle example: http://jsfiddle.net/3h5kfv2j/
This can be implemented in vanilla javascript too, but you will need to find a library that does this or code it yourself.
Here is some sample code of a vanilla implementation I just made: http://jsfiddle.net/4n4w3uqr/
I have a class written in JavaScript called populateTabs. Inside a method I need to initialise different methods like:
populateTabs.facebookStatus();
populateTabs.twitterStatus();
populateTabs.googleStatus();
etc.
Instead of using conditionals or even a switch statement with multiple cases, I wanted to replace facebook, twitter, google with a parameter I have called channelName.
I had this options:
eval ( 'populateTabs.' + channelName + 'Status()' ); (as I understood this is not proper use)
populateTabs[channelName + 'Status']; (proper use)
I've read that using eval() is not really recommended.
Is there a better and secure solution for my issue? Other than using switch statement or if conditionals. All this are subject of writing less code and I'm curious.
Yes, there is a better technique than eval, and you wrote it in your question:
populateTabs[channelName + 'Status']; (proper use)
What more do you want? As you stated, this is the proper way of doing it.
how do i use this code with jquery,
i know it's easy but it doesn't work for me.
document.getElementsByTagName('html')[0].innerHTML.replace(/<!--|-->/g,'')
$('html')[0].innerHTML.replace(/<!--|-->/g,'');
If your intention is to generate a new string where all <!-- and --> are removed then your code works just fine. If not then you probably should be reminded that in javascript, a String's replace() method does not replace anything in that string, it generates a new string. So:
var html = document.getElementsByTagName('html')[0];
html.innerHTML = html.innerHTML.replace(/<!--|-->/g,'');
But your question is very odd. Why would you want to do this? Perhaps you want to uncomment some commented out code? This does not look like something that is safe to do.
This should work for you. Remember you can use javascript and jQuery together. Try this:
$("<html>").html($("<html>").html().replace(/<!--|-->/g,''));
Probably not the most elegant solution, but should work. Are you familiar with:
http://visualjquery.com/