Make comma separated list from different paths - javascript

I have list of paths as follows in multiple lines.
abc/xyz/../a1.txt
abc/xyz/../a2.txt
abc/xyz/../a3.txt
abc1/xyz/../a4.txt
abc1/xyz/../a5.txt
abc1/xyz/../a6.txt
i want to remove all paths and extract only file names as follows
"a1.txt","a2.txt","a3.txt" and
"a4.txt","a5.txt","a6.txt"
pls help me.

Let's say the list of paths is stored in one string:
var paths= "abc/xyz/../a1.txt"
+ "\n" + "abc/xyz/../a2.txt"
+ "\n" + "abc/xyz/../a3.txt"
+ "\n" + "abc1/xyz/../a4.txt"
+ "\n" + "abc1/xyz/../a5.txt"
+ "\n" + "abc1/xyz/../a6.txt";
You just need to split it by lines and reduce each entry to file name (e.g. by using regex):
var fileNamePattern = /[^\/]+$/;
var fileNames = paths.split("\n").map(function (entry) {
return fileNamePattern.exec(entry)[0];
}
For more information about how to use regex look at this link and here you can find how to use the map method.
Update
Here you can find an example

You could use regular expressions to convert a multi-line string with paths into an object that will have an array of file names per folder, where the folder name is used as the object's property name:
// Test data, with some border cases:
var paths = " abc/xyz/../a1.txt\n" +
"abc/xyz/../a2.txt\r\n" +
" \n" +
" no-folder.txt \n" +
"abc/xyz/../a3.txt \n" +
" abc1/xyz/../a4.txt\n" +
"abc1/xyz/../a5.txt\n" +
"abc1/xyz/../a6.txt\n" +
" ";
var filesPerFolder = paths.split(/\r\n|\n/).reduce(function (filesPerFolder, path) {
path = path.trim();
if (path.length) {
var folder = path.replace(/[^\/]*$/, '');
(filesPerFolder[folder] = filesPerFolder[folder] || []).
push(path.substr(folder.length));
}
return filesPerFolder;
}, {});
filesPerFolder will be
{
"abc/xyz/../": [
"a1.txt",
"a2.txt",
"a3.txt"
],
"": [
"no-folder.txt"
],
"abc1/xyz/../": [
"a4.txt",
"a5.txt",
"a6.txt"
]
}
The above code:
recognises LF or CRLF line breaks
skips white-space around paths
skips empty lines
can handle lines that have file names without folder prefix
Here is a fiddle where you can type the list as input, press the Go button and see the Json encoded filesPerFolder.
There are plenty of ways to work with that object. For instance, you could print out the contents as follows:
Object.keys(filesPerFolder).forEach(function(folder) {
console.log('Contents of folder "' + folder + '": '
+ JSON.stringify(filesPerFolder[folder]));
});
This will output (with the example data above):
Contents of folder "abc/xyz/../": ["a1.txt","a2.txt","a3.txt"]
Contents of folder "": ["no-folder.txt"]
Contents of folder "abc1/xyz/../": ["a4.txt","a5.txt","a6.txt"]
Or, if you want to print each of the files with prefixed folder (which would be a clean version of the input):
Object.keys(filesPerFolder).forEach(function(folder) {
filesPerFolder[folder].forEach(function(file) {
console.log(folder + file);
});
});
Output:
abc/xyz/../a1.txt
abc/xyz/../a2.txt
abc/xyz/../a3.txt
no-folder.txt
abc1/xyz/../a4.txt
abc1/xyz/../a5.txt
abc1/xyz/../a6.txt

Assuming this is string, first store different paths inside an array using split for newline in the string:
arr = str.split(/\n/);
Then loop over array and use pop to store file name in another array(say file_names):
file_names.push(arr[i].split('/').pop())

Related

Removing "," at the beginning of a line CSV

i want to convert a .csv file and write a new one. However I am not able to remove the first , i am kinda stuck here and it is driving me crazy.
This is my code:
var extractedtasks = tasks.slice(0, 3)
var extractedtasksformated = extractedtasks.toString().replace(/,$/g, "\n")
let csvformat = "EMAIL,PASSWORD,MAILBOX"
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksformated.replace(/,^/g,
""))
console.log(chalk.green("Successfully updated the CSV file"))
That's the output i am getting in the newly generated file
EMAIL,PASSWORD,MAILBOX
example1#gmail.com,Password123,example#gmail.com:password
,example2#gmail.com,Password123,example#gmail.com:password
,example3#gmail.com,Password123,example#gmail.com:password
Output extractedtasks:
[
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
Output extractedtasksformated:
,example3#gmail.com,Password123,example#gmail.com:passwordxample#gmail.com:password
Because extractedtasks is an array, instead of converting it to a string you should just join it with the expected separator:
extractedtasks = [
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
extractedtasksJoined = extractedtasks.join("\n")
// "example1#gmail.com,Password123,example#gmail.com:password\r\nexample2#gmail.com..."
// depending on the target line separator, you should also probably
// remove the "\r"
extractedtasksJoined = extractedtasksJoined.replace("\r", "")
// finally
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksJoined + "\n")

Convert a string with function calls to an array

I need to convert this function call to a simple array[] but it's not working for some reason.
Here's the fiddle
var LongCombinedReady = $('#GeoImageLat').val(exifObject.GPSLatitude + "," + "'" + exifObject.GPSLatitudeRef + "'")
var LatCombinedReady = exifObject.GPSLongitude + "," + "'" + exifObject.GPSLongitudeRef + "'"
//an attemp to take the values and convert them to an array but it doesn't work.
var LongCombined = [LongCombinedReady];
var LatCombined = [LatCombinedReady];
I've commented it all out in the fiddle also here's an image with GeoCoords if you don't have one for testing.
Test Geotag image
Basically I read the images Geotag and then convert the tag from DMS to DD so it can be used for something like Google maps.
There are three problems:
you are missing an apply in line 49
you are applying array with one item being a string while function you are applying to expects four parameters
at line 43 LongCombinedReady is an jQuery object

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

convert html into javascript string

I'm getting some html from node-request and I want to place that html into my javascript code as strings:
<div id='frontpage'><div set-href="'/user/' + (user | encodeURIComponent)">userlink</div></div>
The goal is to get an output like this for angularjs:
var createCache = function (path, template) {
return "\n $templateCache.put('" + path + "',\n '" +template + "'\n );\n";
}
This code is too naive, there are issues with quotes and other potential problems. How could it be done correctly? Is there a way to get the string from node-request itself? Thanks.

Repeat a function in javascript for "n" times to download text in parts

I would like to download text in parts and add it to a file "foobar" by repeating the download and write function from "data1" to "datan" where n is the last piece of the text.
This needs to be done as the text file is too big to be written directly into "foobar".
My current solution (snippet) is:
var data1 = "AAAAA";
var data2 = "BBBBB";
....
path += '/foobar';
....
downloadfunction(['echo "'+data1+'" >> '+path]);
downloadfunction(['echo "'+data2+'" >> '+path]);
The code works, but my main issue is with the last two lines. Is there a way to make the code more elegant by repeating "downloadfunction" from "data1" to datan"? "n" is a known, but large, number.
Put the data in an array, then you can loop and modify your function to take data and path as arguments:
var data = ['AAAAA', 'BBBBB', 'CCCCC'];
function download(data, path){
save("echo " + data + " >> " + path);
}
...
path += '/foobar';
...
data.forEach(function(d){
download(d, path);
});

Categories

Resources