Javascript array changer - javascript

How change strings in javascript arrays. I want to change array codes to strings.
How change strings in javascript arrays. I want to change array codes to strings.
How to get this;
var _0x1576 = ["SayHello", "GetCount", "Message : ", "You are welcome."];
function NewObject(_0x7aa7x2) {
var _0x7aa7x3 = 0;
this.SayHello = function (_0x7aa7x4) {
_0x7aa7x3++;
alert(_0x7aa7x2 + _0x7aa7x4);
};
this.GetCount = function () {
return _0x7aa7x3
};
}
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
from;
var _0x1576 = ["SayHello", "GetCount", "Message : ", "You are welcome."];
function NewObject(_0x7aa7x2) {
var _0x7aa7x3 = 0;
this[_0x1576[0]] = function (_0x7aa7x4) {
_0x7aa7x3++;
alert(_0x7aa7x2 + _0x7aa7x4);
};
this[_0x1576[1]] = function () {
return _0x7aa7x3
};
}
var obj = new NewObject(_0x1576[2]);
obj.SayHello(_0x1576[3]);

EDIT: So you have some code, where all the variable names have been replaced by numbers or indices into this global array of names, and you would like to be able to read it. There is already an answer to this question, which contains links to a bunch of useful deobfuscation tools.
Your case here looks fairly trivial - it appears that you could just do a string search and replace, substituting in the array value every time it is indexed. The regexp /_0x1576\[(\d+)\]/g should find everything that accesses the variable _0x1576 with an integer index. The inner group (\d+) should give you the index with which it was found. You could use something like this to do deobfuscate your source. However, some of the names have been lost in the obfuscation process; i.e. the name of the parameter 0x7aa7x4 in the SayHello function can't be restored. You will have to read the method, understand what its' purpose is, and try to come up with a meaningful name yourself.
One question though - just how much code do you have like this? If there are only a few names in the array of strings, then #Nina Scholz's suggestion seems fairly reasonable. Just go through them one by one, in a text editor, and use the 'Find and Replace' functionality.

Related

Create a variable with two arrays made from two .map() looking for match or intersection

The point is I'm not an expert with JS so excuse me if my code is a big mistake, in fact I'm just training to learn making a huge "Frankenstein" from a research around the web.
I want to take two set or lists of values input by the user and compare them looking for matches with js and jquery.
First, I take the values from two groups of inputs (diferenced by class) with .map(), this to have the values to create the arrays.
var x = $(".row_a").map(function() {
return this.value;
}).get();
var y = $(".row_b").map(function() {
return this.value;
}).get();
Then I'm traying to create one variable that contain the two arryas separatly (here Is when think I have the problem) if I "hardcode" the arrays the next part of the script works as expected, but if I use the the first two variables made above, the script just crash.
var arrays = [
[x],
[y]
];
In the third part (I really don't understand this part of the code in deep) I run the script that compare the two arrys on the second variable and then append a paragraph with the result.
var result = arrays.shift().reduce(function(res, v) {
if (res.indexOf(v) === -1 && arrays.every(function(a) {
return a.indexOf(v) !== -1;
})) res.push(v);
return res;
}, []);
$(".match").append("<div>Numbers " + result + " match in both lists</div>");
Somebody can help me to undersnatd whats wrong or giveme a clue or link that can help?
curious: if I use the same variable twice in the variable that contain the arrays, the script works and finds four matches (I think is right becouse compare the same array)
DEMO
--
EDITED:
Thanks to #KarlReid and #Potorr. I didn't know the intersection concept in javascript, so now I know a better way to achive the result. I'll read more about it to try understand the answer in deep.
Thanks to #Alexandru for letting me know the sintax error, it'll be very basic and usefull henceforth.
Final Result: DEMO
(I'll be edit the tittle of the post to try improve the search for others with the same question in the future.)
This works, explanation in-line:
$(".action").click(function() {
var x = $(".row_a").map(function() {
return this.value;
}).get()
var y = $(".row_b").map(function() {
return this.value;
}).get()
// this is not really needed, if you want it:
// x, y are already arrays, so you don't need to wrap them with []
// var arrays = [
// x,
// y
//];
// intersection, adapted from: https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
// if you use the "arrays" variable, then change x to arrays[0] and y to arrays[1]
//var intersection = x.filter(function(n) {
// return y.indexOf(n) !== -1;
//});
// the intersection function posted by #KarlReid is actually better and faster:
var intersection = x.filter(Set.prototype.has, new Set(y));
// create the result string
var result = intersection.join(',')
$(".match").append("<div>Numbers " + result + " match in both lists</div>");
});
Edit: Changed intersection function to the one posted by #KarlReid
Although better solutions exists, as pointed out by comments the Potorr's answer, the only problem with the code posted is this:
var arrays = [
[x],
[y]
];
x and y are already arrays, so you don't need to wrap them with [ ]. The code works if you simply replace the above code with:
var arrays = [
x,
y
];
Updated demo

How to treat array result as array Javascript?

i want to for loop my array result as array because i use nested loop.
Here is my code
var isp = ["yahoo", "gmail"];
var yahoo = ["#yahoo.com", "#rocketmail.com", "#ymail.com"];
var gmail = ["#gmail.com"];
for(x=0;x<isp.length;x++){
//Should alert 3 Because var yahoo contains 3 element
//Should alert 1 because var gmail is contain 1 element
alert(isp[x].length);
for(y=0;y<isp[x].length;y++){
//Should alert #yahoo.com, #rocketmail.com and so on
alert(isp[x][y]);
}
}
Here is my JSFiddle https://jsfiddle.net/4v272ghL/1/
Try this:
https://jsfiddle.net/4v272ghL/2/
var isp = ["yahoo", "gmail"];
var providers = {
'yahoo': ["#yahoo.com", "#rocketmail.com", "#ymail.com"],
'gmail': ["#gmail.com"]
};
isp.forEach(function(v, i) {
console.log(v);
providers[v].forEach(function(domain, index) {
console.log(domain);
});
});
You're using a JS object to hold the arrays of domains instead. Using this, you can access each provider's data dynamically.
Maybe you don't need so many arrays? Lets use an object instead.
var isps = {
yahoo: ["#yahoo.com", "#rocketmail.com", "#ymail.com"],
gmail: ["#gmail.com"]
};
for(isp in isps) {
var providers = isps[isp];
document.write(isp + " has " + providers.length + " provider(s):<br/>");
providers.forEach(function(domain) {
document.write(domain + "<br/>");
});
};
This works because instead of looping through an array and trying to access different variables with the same name, you can instead simply loop through the keys of an object (which are the same as that first array) and use it to access the values of that object (which are the same as in the other variables you had before).
Note that I've changed your alerts to things that will be more informative in running the code snippet. Of course, once you've got access to these values isp, providers and domain, you can do whatever you like with them - you don't need to document.write them.
There are a few benefits to this method. For instance, as we're only human, what if this happened:
var isp = ["yahoo"];
var yahooo = ["#yahoo.com"];
There's a dependency on the values in isp and the variable names being exactly the same. A simple error like above ("yahooo" instead of "yahoo") would prevent the code from working, and a one letter bug like that could be quite difficult to find if you don't know what you're looking for.
If you're to come back and add or modify these values often, this could become a concern. With the object pattern, it's cleaner and more self-contained.
One potential concern with this solution, however, is if the order in which these providers are looped through is important (i.e. if you always need "yahoo" to output before "gmail"). Currently JavaScript states the following in regards to objects: "It is an unordered collection of properties". This could be subject to change in ES6 (we're currently on ES5). Read more about this particular issue here:
Does JavaScript Guarantee Object Property Order?
You will need to eval the isp[x] in order to get the array names of the other two. For example:
var isp = ["yahoo", "gmail"];
var yahoo = ["#yahoo.com", "#rocketmail.com", "#ymail.com"];
var gmail = ["#gmail.com"];
for(x=0;x<isp.length;x++){
//Should alert 3 Because var yahoo contains 3 element
//Should alert 1 because var gmail is contain 1 element
alert(isp[x].length);
for(y=0;y<eval(isp[x]).length;y++){
//Should alert #yahoo.com, #rocketmail.com and so on
alert(eval(isp[x])[y]);
}
}
This is clear i guess right ?
:D
var ispAndData = [
["yahoo", ["#yahoo.com", "#rocketmail.com", "#ymail.com"]],
["gmail", ["#gmail.com"]]
];
for (x = 0; x < ispAndData.length; x++) {
//Should alert 3 Because var yahoo contains 3 element
//Should alert 1 because var gmail is contain 1 element
document.write(ispAndData[x][0] + " -> ");
document.write(ispAndData[x][1].length + "</br>");
for (y = 0; y < ispAndData[x][1].length; y++) {
//Should alert #yahoo.com, #rocketmail.com and so on
document.write(ispAndData[x][1][y] + "</br>");
}
document.write("</br>");
}

Refer to an array using a variable

I am writing a page that collects serial numbers for parts installed in an assembly. I want to validate the user input on the client-side, if I can.
So if I have multiple dense arrarys, how can I refer to them using a varaiable? For instance, say I have three densely packed arrays who's names represent part numbers, and who's values represent serial numbers (that have been consumed in other assemblies).
arr_PN-123-ABC = ('SN0123','SN0124','SN0125')
arr_PN-456-DEF = ('SN00333','SN00334','SN00335')
arr_PN-789-GHI = ('SN-0001','SN-0002','SN-0003','SN-0004')
function fcnValidateSN(_givenPN, _givenSN) {
//make sure the given values are not null or empty...
//derive the array of serial numbers that coorsponds to the given part number...
var vArrName = "arr_" + vGivenPN;
//loop thru the array of serial numbers to determine if the given sn was already used...
for(var x=0; x < vArrName.length(); x++) {
if(vArrName[x]==_givenSN) {
alert("Serial number '" + _givenSN + "' was already used in another assembly.");
theForm.txtPN.focus();
return;
}
} //end 'for' loop
} //end fcnValidateSN()
So the problem is that 'vArrName' is a string with a value of 'arr_' instead of a refernece to an array who's name is 'arr_'.
I tried wrapping it with the eval() function, but eval() treats dashes as minus signs.
One other note: I cannot use jquery for this effort.
Thank you
You cannot generate a reference to a variable declared with var (except see below). You can use dynamic property names to refer to properties of objects, so:
var arrays = {
"arr_PN-123-ABC": ['SN0123','SN0124','SN0125'],
"arr_PN-456-DEF": ['SN00333','SN00334','SN00335'],
// ...
};
Then:
console.log( arrays["arr_PN-" + num + "ABC"][0] ); // SN0123
Note that you cannot use "-" in a variable name, but you can use it in an object property name.
The exception to not being able to access var variables by dynamic name is made for global variables in a browser. Those variables all end up as properties of the window object.
An array in JavaScript is delimitated by [ and ], not ( or ).
A valid JavaScript variable name can't contain '-'
The length property of an array isn't a function
Well, I've done some (actually, a lot of) adjustments in your code, but I think this is what you need:
var serialGroups = {
PN_123_ABC: ['SN0123','SN0124','SN0125'],
PN_456_DEF: ['SN00333','SN00334','SN00335'],
PN_789_GHI: ['SN-0001','SN-0002','SN-0003','SN-0004']
};
function validateSerial(groupName, sn) {
var serials = serialGroups[groupName];
for(var i=0; i < serials.length; i++){
if(serials[i] == sn) {
alert("Serial number '" + sn + "' was already used in another assembly.");
//Do whatever you want here
return;
}
}
}
Use a single object that has the arrays as elements:
var arr_PN = {
'123-ABC': ('SN0123','SN0124','SN0125'),
'456-DEF': ('SN00333','SN00334','SN00335'),
'789-GHI': ('SN-0001','SN-0002','SN-0003','SN-0004')
}
And then reference using:
var vArrName = arr_PN->{vGivenPN};

adding chr to the number Prototype

I have the following function:
var chr = function(X) {
return String.fromCharCode(X)
}
But I would like to use i.chr() instead of chr(i).
Q: How do I add chr() to the number prototype?
Number.prototype.chr = function() {
return String.fromCharCode(this);
}
var n = 33;
console.log(n.chr());
http://jsfiddle.net/CXWeV/
Also, as Bryan points out, the following will work:
console.log((33).chr());
console.log(Number(33).chr());
But, the following does not work:
33.chr();
EDIT: Although, as Gumbo points out, this does:
33..chr();
As well as a check if the property already exists (see Erik's answer for another way to check):
if (!Number.prototype.chr) {
Number.prototype.chr = function() {
return String.fromCharCode(this);
}
}
if (!Number.prototype.hasOwnProperty('chr')) {
Number.prototype.chr = function() {
return String.fromCharCode(this);
};
}
To use this the number must be in a variable or wrapped in parentheses. Be aware that converting a scalar number to a Number object (called boxing) has an overhead. If you are doing the conversion repeatedly on the same value, you'll want to explicitly convert it to an object first with Number().
Note that simply doing String.fromCharCode might be easier or more clear in some situations.
The normal way, really. Note the importance of surrounding the number in parentheses (or storing it in a variable), as a dot would normally indicate a decimal point:
Number.prototype.chr = function () {
return String.fromCharCode(this);
}
alert((97).chr()); // alerts "a"
I'm not sure whether this works in all browsers, but I'm assuming it does.
Interactive Example

Get URL array variables in javascript/jquery

I've got a bunch of parameters being passed to a page by URL variables. The URL looks sort of like:
file.aspx?category[]=1&category[]=7&category[]=3&id=8az
Using the jQuery getUrlParam extension I can get url variables very easily, but rather than returning category as an array (which is what I want) it gets returned as null.
Is there a way for me to read these into a javascript array?
I previously pointed to this question: Get QueryString values with jQuery - but as #Crescent Fresh pointed out, those examples don't deal with arrays in the query string (and besides, they're a bit slow I think.
So I cooked up my version of this function:
function getQueryString () {
var ret = {};
var parts = (document.location.toString().split('?')[1]).split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i].split('=');
// so strings will be correctly parsed:
p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
if (p[0].search(/\[\]/) >= 0) { // then it's an array
p[0] = p[0].replace('[]','');
if (typeof ret[p[0]] != 'object') ret[p[0]] = [];
ret[p[0]].push(p[1]);
} else {
ret[p[0]] = p[1];
}
}
return ret;
}
But there are caveats. It will only work on a correctly formed query string - there's no error detection. Also, it does not work on numbered/indexed arrays.. that is when your array is defined in the query string as:
?category[3]=1&category[4]=7&category[20]=3&id=8az
It would be trivial to add to the .search() query a regex for finding that as well, but I'm not the best regex expert... anybody got ideas?
Shouldn't it be: file.aspx?category=1&category=7&category=3

Categories

Resources