Execute string comma character ',' as code - javascript

I have this code block:
var comma_decoded = window.btoa(',');
var comma_encoded = window.atob(comma_decoded);
var log = eval(comma_encoded);
var x = 1 log y = 2;
console.log(x + ' ' + y);
but, I can't execute ',' character as code.
I need '1 2' output, so log variable must work like comma (,)
Thank you.

In javascript, you cannot use variables as operators or language-specific tokens.

Related

Converting Strings to Template Literals in ES6

Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);
But this alerts as ${a + b}, so it just does one level of substitution.
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);
This still alerts as ${a + b}.
Tried being even more clever:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);
This alerts as ${a} + ${b}.
Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!
Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));

why do i have to declare javascript variable with an empty value?

why must i declare the var msg = ' '; and not just var msg; and also why msg += 'Round ' + roundNumber + ':';' and not just msg = 'Round ' + roundNumber + ':';.... why should i add + sign before equals ?
var score = [24, 32, 17];
var arrayLength = score.length;
var roundNumber = 0;
var i;
var msg = '';
for (i = 0; i < arrayLength; i++) {
roundNumber = (i + 1);
msg += 'Round ' + roundNumber + ':';
msg += score[i] + '</br>'
}
document.getElementById('answer').innerHTML = msg;
output of the above code:
Test 1:24
Test 2:32
Test 3:17
output of the code when msg is declared only rather than giving an empty value and assigning msg without the plus (+) sign:
Test 3:17
You have confused a number of Javascript concepts.
Firstly, Javascript variables must be declared but do not have to be initialised. To declare a Javascript variable, you use the var keyword. For example, var msg; is valid Javascript code. As well as declaring a variable, you can optionally initialise it using an = sign. So, for example, var msg = ''; declares the msg variable and initialises it to an empty string. Importantly for you, if you do not initialise a Javascript variable, it is set to a special type of variable called undefined.
The second Javascript concept you have confused is assignment and calculation. In Javascript, you use the = sign to assign a value to a variable. So, for example x = 1; sets the value of the x variable to 1. The += operator is a shorthand operator. So, x += y; is exactly the same as x = x + y;. The crucial difference is that the = operator overwrites the existing value of the variable, whereas += uses the existing value to calculate a new value.
So, in the specific case of your code, you have used the += operator on the msg variable. As explained, the += operator performs a calculation on the existing value of the variable. So, this is why you had to initialise your variable when you declared it - otherwise you would have been performing a += on an undefined variable - which, in your case, does not perform the string concatenation that you expected.
The specific instances on when you should use what very much depends upon what the goal of your code is.

Javascript - parseInt returns strange values for WebSocket data

I'm getting some strange behaviour when using the parseInt().
webSocket.onmessage = function (event) {
var raw = event.data;
alert(raw);
var data = raw.split(":");
alert("lat:\"" + data[0] + "\" lon:\"" + data[1] + "\"");
var x = parseInt(data[0]);
var y = parseInt(data[1]);
alert("lat:" + x + " lon:" + y);
}
The first alert outputs: 100:100 - this is the string sent from the server.
The second alert outputs: lat:"100" lon:"100" - which is fine
However, the third alert outputs: lat:1 lon:NaN
What could cause this?
UPDATE:
The problem was the encoding on the server side generating some invisible unwanted characters. I updated the server code and the problem was gone. Working solution.
My guess is that, there are non-printable characters like spaces, tabs, etc. in your data that's why you're getting NaN after split.
You can use regex to get the data as follow. Using this way, you don't have to worry about non-printable characters as only digits are selected by regex.
var raw = '100:100 ';
var data = raw.match(/\d+/g);
var x = parseInt(data[0], 10);
var y = parseInt(data[1], 10);
document.write('x=' + x + ' y=' + y);
The above regex will select all the digits from raw string.
I agree with #Tushar. Thus, belive some special characters are being parsed in the raw = even.data; (can't replicate here, although)
The code below seems to work fine, you might adjust to yours and test it:
<script type="text/javascript">
var raw = '100 :100asd';
var data = raw.match(/[0-9]+/gm);
alert(raw); // console.log(raw);
var data = raw.split(":");
alert("lat:\"" + data[0] + "\" lon:\"" + data[1] + "\"");
var x = parseInt(data[0]);
var y = parseInt(data[1]);
alert("lat:" + x + " lon:" + y);
</script>

Prepend a number with $ in javascript

I have a small script ( using nouislider )
I wish to prepend the rangeThing values with $ sign as we are outputting prices.
Code I have is:
$("#slider").noUiSlider({
range: [0, 1000000]
,start: [350000, 700000]
,handles: 2
,step: 50000
,slide: function(){
var values = $(this).val();
$("span.rangeThing").text(
values[0] +
" - " +
values[1]
);
}
,serialization: {
to: [$("#exTO"),$("#exFR")]
,resolution: 1
}
});
The javascript creates a span like <span class="rangeThing"></span>
The output format is like this 200000 - 350000
I would like to format with ( commas ) as thousand separators, but thats gonna get messy. So I am trying to prepend the 2 sets of values with $ sign to signify a price.
So resultant output is like $200000 - $350000
I tried changing the values to something like this, but that didnt work lol.
$("span.rangeThing").text(
+ "$" + values[0] +
" - " +
+ "$" + values[1]
);
I am not sure if I am on the right track, and that the fact I am trying to echo $ could be the culprit, and perhaps I should use unicode, either way it isnt working.
Help appreciated
The problem is that the unary plus in Javascript implcitly converts the operand to a number. This means that
+ "$"
actually evaluates to NaN.
Just place the + operator only between terms and things should go as you expect.
Do it in one line to see what's going on:
You are starting with a +
The third line has double +
One line would be easier to read:
$("span.rangeThing").text("$" + values[0] + " - $" + values[1]);
Well, in your example there appears to be an extra + operator in the example you gave. As you see in the example you gave:
$("span.rangeThing").text(
values[0] +
" - " +
values[1]
);
This will result in the string "1 - 2", assuming values = [1, 2]. You should be able to simple add on the $ by doing something like:
$("span.rangeThing").text(
"$" + values[0] +
" - " +
"$" + values[1]
);
As you've probably realized, the example you posted has some syntactic errors -- you have +'s everywhere! One thing to be aware of -- if you are trying to combine strings in the same line as numeric operations, you will need additional parentheses. So, if you had:
var string = "foo"+2+3+"bar";
your string would be:
foo23bar
whereas if you had:
var string = "foo"+(2+3)+"bar";
your string would be:
foo5bar
In addition, here's how you can add the commas if you want...
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
To use it, just add the function to your file, and use it like this...
$("span.rangeThing").text("$" + addCommas(values[0]) + " - " + "$" + addCommas(values[1]));

js add comma at Sextillion values

I use one small code js to add comma to value:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
I have problem when try to add comma to big values like sextillion values.
Eg.
addCommas(1000000) //return correct "1,000,000"
but if use big values like this
addCommas(50949024266983356472874) // return wrong "5.094902426698335e+22"
What or where I do wrong?
Your input might already be a float. Numbers larger than 2^32 tend to be like this. Make sure your input is a string and your function will run fine.
JavaScript doesn't have int and float types. Instead it just has a Number type and it will decide on it's own when to use which.
When you do
nStr += '';
You're asking javascript to first convert your number to a string. That's when it decides to write it as "5.094902426698335e+22". The problem isn't in the rest of your algorithm.
The conversion is described here in ecmascript
If your number is stored in a string the following function will achieve what you are asking for.
function addCommas( txtNum ) {
var parts = txtNum.split(".");
parts[0] = parts[0].reverse().replace(/(\d{3})/g, "$1,").reverse();
return parts.join(".");
}
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
addCommas( "-50000000000000000000000000000000000000000.0000" );
// => -50,000,000,000,000,000,000,000,000,000,000,000,000,000.0000

Categories

Resources