custom specifier in javascript/jquery - javascript

i want to format the numeric value in java script /jquery like that doing in C#. please refer below link.
http://msdn.microsoft.com/en-us/library/0c899ak8%28v=VS.90%29.aspx#SpecifierD
what are the formats currently we can do in javascript (currency, percentange,numeric).
i know that jquery.globalize script will do some formats like ($,%) i want to know what are the formats we can perform or implement in javascript.
is there any in build function for format the date time like format in C#
(dd/mm/yy)
Thanks,
Siva

Personally, I am not a great fan of the "plugins with jam" and "plugins with ketchup" approach to solving problems. As a general rule when you find yourself thinking "How can I do X in JavaScript like I do it in C# or PHP" it is well worth checking out PHP JS. In the present instance I suspect the sprintf function will do the trick.
Another useful function is this
String.prototype.format = function (args)
{
var newStr = this;
for (var key in args){newStr = newStr.replace('{' + key + '}', args[key]);}
return newStr;
}
//for example
console.log("You owe me ${aa}".format({aa:100}));
The string prototype extension is not my own work - I found it somewhere. Maybe here on SO, I cannot remember.

Related

Javascript analogue of Python's string.encode('UTF-8')

I have a string that represents some binary data, looking like:
\x89PNG\x1a\x00\x00\x00IHDR\x00\x00 etc
I need to post this string to some API, etc. AS IS but the problem is that Javascript automatically converts it to
PNG etc
.escape, .encodeURI.. etc don't help
In Python such conversion can be done like string.encode('UTF-8') but I can't find nothing like that in JS.
Maybe someone knows the library or something that may help?
In Javascript we usualy use Base64 for this.
You can do something like
var encodedData = window.btoa(stringToEncode);
var decodedData = window.atob(encodedData);
You may also find this interesting
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
Or reference https://stackoverflow.com/a/22373061/6302200

Is there a way to compress a long string to a smaller one and vise versa by code?

I am working on a plugin for an existing web-based tool in JavaScript.
We are collecting data and store it in a string like this:
"2.545,3.552,8.568;2.553,9.898,6.542;..." and so on.
The problem is, that we reach an export limit of 64k characters too fast.
I wanted to ask - and excuse me if it is a dumb question - if someone knows
of an algorithm or method we could use to compress the string before we export it. I am sure that it is technically possible but it certainly exceeds my skills as a programmer.
Thanks for any tips, link or suggestion.
lz-string looks like it will work.
var string = "2.545,3.552,8.568;2.553,9.898,6.542";
alert("Size of sample is: " + string.length);
var compressed = LZString.compress(string);
alert("Size of compressed sample is: " + compressed.length);
string = LZString.decompress(compressed);
alert("Sample is: " + string);
<script src="https://cdn.jsdelivr.net/gh/pieroxy/lz-string/libs/lz-string.js"></script>
I would suggest you use a dedicated Web Worker for this. There is a pretty good explanation on Using Web Worker on the mozilla developers page.

Javascript Int vs BigInt libraries

From the JavaScript documentation we see that, due to using double-precision floating-point format numbers, to go beyond 9007199254740991 a library is needed.
We'll find a handy list of libraries to achieve that here.
While searching on homomorphic encryption I came across this question.There you can find this link to an in-browser implementation of Pailler.
After inspecting the code I saw the source included jsbn.js which made total sense (as you are gonna need BigInts for the crypto). However, the way it deals with the numbers to be encrypted looked a bit odd to me.
$('#btn_encrypt').click(function(event) {
var valA = parseInt($('#inputA').val()),
valB = parseInt($('#inputB').val()),
startTime,
elapsed;
startTime = new Date().getTime();
encA = keys.pub.encrypt(nbv(valA));
elapsed = new Date().getTime() - startTime;
$('#encA').html(encA.toString());
$('#encAtime').html(elapsed);
From using parseInt and nbv function nbv(i) { var r = nbi(); r.fromInt(i); return r; } it seems clear that they are relying on integers to create the BigInt that will then be encrypted.
Does that make any sense at all? Even less so when having a function to create BigInts directly from strings // (protected) set from string and radix
function bnpFromString(s,b) { ...} That link has been referenced in several other answers both in here, and the crypto site and as I said I am a newbie at JS so I wanted to check whether this is indeed an contraindicated way of implementing Pailler or I have understood something wrong.
Thanks a lot for helping out!
It appears that the Pailler implementation you linked to is intended as a proof-of-concept demo rather than as a full-fledged implementation. Presumably, the author intended it for use only on toy examples such as (36+14)*7 or (97+5)*11 rather than "real" examples involving hundreds of digits.

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 filter using Regex and javascript?

I have some text in an element in my page, and i want to scrap the price on that page without any text beside.
I found the page contain price like that:
<span class="discount">now $39.99</span>
How to filter this and just get "$39.99" just using JavaScript and regular expressions.
The question may be too easy or asked by another way before but i know nothing about regular expressions so asked for your help :).
<script language="javascript">
window.onload = function () {
// Get all of the elements with class name "discount"
var elements = document.getElementsByClassName('discount');
// Loop over each <span class="discount">
for (var i=0; i < elements.length; i++) {
// get the text, e.g. "now $39.99"
var rawText = elements[i].innerHTML;
// Here's a regular expression to match one or more digits (\d+)
// followed by a period (\.) and one or more digits again (\d+)
var priceAsString = rawText.match(/\d+\.\d+/)
// You'll want to make the price a floating point number if you
// intend to do any calculations with it.
var price = parseFloat(priceAsString);
// Now what do you want to do with the price? I'll just write it out
// to the console (using FireBug or something similar)
console.log(price);
}
}
</script>
document.evaluate("//span[#class='discount']",
document,
null,
XPathResult.ANY_UNORDERED_NODE_TYPE,
null).singleNodeValue.textContent.replace("now $", "");
EDIT: This is standard XPath. I'm not sure what kind of explanation you're seeking. For outdated browsers, you will need a third-party library like Sarissa and/or Java-line.
Regexes are fundamentally bad at parsing HTML (see Can you provide some examples of why it is hard to parse XML and HTML with a regex? for why). What you need is an HTML parser. See Can you provide an example of parsing HTML with your favorite parser? for examples using a variety of parsers.
Patrick McElhaney's and Matthew Flaschen's answers are both good ways to solve the problem.
as Matthew Flaschen suggested, XPATH is a better way to go, if you know something about the node structure of the target document (and since you provided an example, you seem to). If you don't know the node structure, regexes are still lousy for parsing XML.
some more resources to kick-start you:
XPath in Javascript: Introduction
DOM Parsing With XPath and JavaScript
Mozilla dev-center: Introduction to using XPath in JavaScript
I've also found the FireFox extension combo of DOM Inspector and XPather to be an invaluable tool for deriving and testing XPath expressions on a given page. (If you're using another browser -- well, I don't know).

Categories

Resources