Unable to Split the array element in Javascript - javascript

I am quite new to Javascript. I wanted to get the filename and extension from a specific folder. For that i am using ActiveXObject and going to the folder using GetFolder and then enumerating through each individual files. The code is given below.
<html>
<script type='text/javascript'>
var myFileNameArray = new Array;
var myFileNameArray = new Array;
function ReadFromFile()
{
var i;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fsofolder = fso.GetFolder("C:\\Users\\Divya.R");
var colFiles = fsofolder.Files;
var fc = new Enumerator(colFiles);
for (; !fc.atEnd(); fc.moveNext() )
{
msg += fc.item() + ";";
}
myFilePathArray = msg.split(";");
for(i=0;i<=myFilePathArray.length;i++)
{
myFileNameArray[i] = myFilePathArray[i].split("\\");
}
document.write(myFileNameArray[0]);
}
</script>
<body onload='ReadFromFile()'>
</body>
</html>
I will get the complete file path in myFilePathArray from each array element i should get the filename. For that I am trying to split again based on '/' and then thought to get the arraylength-1 th element. However the last document write return be a blank page. It doesnt split the myFilePathArray. Please let me know what is wrong with this.
Regards,
Div

Since \ is an escape character it will be ignored. I have found a solution which worked for me. The code is given below.
var msg = "C:\\Users\\Divya.R\\Data.txt;C:\\Users\\Divya.R\\Test2.csv";
var regex = /\\/g;
var fileName="";
var FilePath = msg.replace(regex, "\\\\");
//document.write(FilePath);
var myArray1 = new Array;
var myArray2 = new Array;
myArray1 = FilePath.split(";");
myArray2 =myArray1[0].split("\\");
for(var i=0;i<=myArray1.length-1;i++)
{
myArray2= myArray1[i].split("\\");
fileName = fileName+myArray2[myArray2.length-1];
}
//alert(myArray2[myArray2.length-1]);
alert(fileName);
Regards,
Divya

A simple substr and lastIndexOf would suffice to get your parts:
var path = "C:\\Users\\Divya.R\\Data.txt";
var fileName = path.substr(path.lastIndexOf("\\") + 1);
var ext = path.substr(path.lastIndexOf('.') + 1); // txt

Related

Search a Spreadsheet for String and return partial row data

Hello stackoverflow community,
I want to create a script to search a google sheet by name, as this file will be deleted at the end of the script. A new file will be uploaded to google drive automatically every week. This will be the basis for the script that will be running weekly.
The code runs fine, but returns undefined in the 4 output cells.
Example Data from a row in the Spreadsheet "LocafoxInventoryData_Automatic":
1||5b8ff4fc3e578c005487dcd5|60.0000|38.6300|19.0000|||2.0000
I would like to retrieve the last number in the above string. (after the last " | " )
I hope someone can help me out. The strings being searched for are the ids of the products: In the above sample "5b8ff4fc3e578c005487dcd5". This id can only be found twice in the sheet. I want to always retrieve the first one. The differnce between the first and the second product IDs are the first number in the string. There are "1" and "2".
function getData() {
var files = DriveApp.getFilesByName('LocafoxInventoryData_Automatic');
while (files.hasNext()) {
var file = files.next();
var id = file.getId()
}
var sheetData = SpreadsheetApp.openById(id).getActiveSheet().getDataRange().getValues();
var sspre = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Vorlage");
var searchString1 = sspre.getRange('I7').getValue();
var searchString2 = sspre.getRange('I8').getValue();
var searchString3 = sspre.getRange('I9').getValue();
var searchString4 = sspre.getRange('I10').getValue();
for(var i=0;i<sheetData;i++)
{
//Column 1 should be searched
if(sheetData[i][0].search(searchString1)!=-1)
{
var rowData1 = sheetData[i];
return rowData1;
}
else if(sheetData[i][0].search(searchString2)!=-1)
{
var rowData2 = sheetData[i];
return rowData2;
}
else if(sheetData[i][0].search(searchString3)!=-1)
{
var rowData3 = sheetData[i];
return rowData3;
}
else if(sheetData[i][0].search(searchString4)!=-1)
{
var rowData4 = sheetData[i];
return rowData4;
}
}
sspre.getRange('D7').setValue(rowData1);
sspre.getRange('D8').setValue(rowData2);
sspre.getRange('D9').setValue(rowData3);
sspre.getRange('D10').setValue(rowData4);
file.setTrashed(true);
}
Returning Partial Row Data with Regex
Okay this is working for me. I have a file named 'LocafoxInventoryData_Automatic' which is a spreadsheet with one sheet. I look for files with that name and if more than one is found I throw error so that you can figure out which one you want.
I then open up the file as a SpreadSheet with openById. I get the product id from the Vorlage sheet column I7,8,9,10 and I wrap them with a regular expression that looks like this ^1\|\|cw8vtfxa5owglp03btv22g9d.\|\|\|(.)$ . Although in the code the backslashes \ have to be \\ double backslashed which took me a while to figure out.
So that get's the numbers at the end and I put them into Vorlage column D7,8,9,10. And then I set the file isTrashed to true. I don't know if you want to return the data so I left the object in there but commented them out. I also removed all of the else ifs.
function getData() {
var filename='LocafoxInventoryData_Automatic';
var files = DriveApp.getFilesByName(filename);
var n=0;
while (files.hasNext()) {
var file = files.next();
var id = file.getId();
n++;
}
if(n>1){throw(Utilities.formatString('Error: More than file named %s', filename));}//Will present an error if there is more than one file
if(id){
var sheetData = SpreadsheetApp.openById(id).getActiveSheet().getDataRange().getValues();//I assumed no headers in this file
var sspre = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Vorlage");
var re1 = new RegExp('^1\\|\\|' + sspre.getRange('I7').getValue() + '.*\\|\\|\\|(.*)$','i');
var re2 = new RegExp('^1\\|\\|' + sspre.getRange('I8').getValue() + '.*\\|\\|\\|(.*)$','i');
var re3 = new RegExp('^1\\|\\|' + sspre.getRange('I9').getValue() + '.*\\|\\|\\|(.*)$','i');
var re4 = new RegExp('^1\\|\\|' + sspre.getRange('I10').getValue() + '.*\\|\\|\\|(.*$)','i');
for(var i=0;i<sheetData.length;i++){
var rD1=re1.exec(sheetData[i][0]);
if(rD1) {
var rowData1 = rD1[1];
}
var rD2=re2.exec(sheetData[i][0]);
if(rD2) {
var rowData2 = rD2[1];
}
var rD3=re3.exec(sheetData[i][0]);
if(rD3) {
var rowData3 = rD3[1];
}
var rD4=re4.exec(sheetData[i][0]);
if(rD4) {
var rowData4 = rD4[1];
}
}
//var rObj={rowData1:rowData1,rowData2:rowData2,rowData3:rowData3,rowData4:rowData4};
sspre.getRange('D7').setValue(rowData1);
sspre.getRange('D8').setValue(rowData2);
sspre.getRange('D9').setValue(rowData3);
sspre.getRange('D10').setValue(rowData4);
file.setTrashed(true);
//return rObj;
}
}
Regular Expression exec method
RegExp
By the way it's quite helpful with sort of a problem to have your own regex tester written in the same language you happen to be developing in. I'm sorry it took me so long. If you run into additional problems let me know.

string.split('/') not giving proper array

I'm having an issue with the following script.
The calling script is:
script src="//192.168.6.10/js/cYJIeCa30E.js
the resulting script needs to be parsed for cYJIeCa30E.js
in this script I have:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
var name = scriptName.split('/');
alert(name);
alert(name) gives comma separated values:
http:,,192.168.6.10,js,cYJIeCa30E.js
but
alert(name[4]) gives ':' not the value after the last '/'
any idea what I am missing?
Thanks
The proper way will be like so:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
var a = scriptName.split('/');
alert(a[4]); //cYJIeCa30E.js
Note You can change the variable a to any other variable. Thanks to Mike C for the MDN link

Get hyper link from a SharePoint list column

I want to get the hyperlinks from a column of a SharePoint 2010 List. Right now the code gives me the hyperlink and the description concatenated together.
`
$(xData.responseXML).SPFilterNode("z:row").each(function () {
content = new Object(); //get new object
content.title = $(this).attr("ows_Title");
content.url= $(this).attr("ows_Url");`
The content.url gives me "http://www.example. ca,%20http://www.example. ca". I have tried split and then the URL doesn't work.
Any help will be greatly appreciated.
Thanks
if I'm understanding you correctly, split should work... here's an encapsulated example:
<a id="yourlinkId">link</a>
<script>
var url = "http://www.example.ca,%20http://www.example.ca";
var n = url.split(",%20");
var a = document.getElementById("yourlinkId");
a.href = n[0];
</script>
combine that with your code and you end up with something like:
$(xData.responseXML).SPFilterNode("z:row").each(function () {
content = new Object(); //get new object
content.title = $(this).attr("ows_Title");
var url = $(this).attr("ows_Url");
var n = url.split(",%20");
content.url = n[0];

javascript copying array to another

i have the following code snippet, where inside for loop the value to contain is not getting assigned, is this is the proper way to copy array to other.??
as here
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var m=grpNameArr.length;
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(m-1);ii++)
{
contain[ii] = groupCn[ii];
cmds[ii] = grpNameArr[ii];
}
If you want to clone an array you can use slice() method as mentioned in this page:
http://www.hardcode.nl/subcategory_1/article_414-copy-or-clone-javascript-array-object
var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
your array declaration is wrong , it should be like :-
var groupcn=["All","All","All","All"];
var grpNameArr=["abc","def","ghi"];
you can use :
var contain=groupcn.concat();
var cmds=grpNameArray.concat();
So, after your edit, I see your problem was that you has some typo's in your variable names.
Replace:
var grpNameArr = groupParm.split("#");
var groupcn= groupCondtn.split("&");
With:
var grpNameArr = groupParam.split("#");
// ^ Missing `a` and `r`.
var groupCn= groupCondition.split("&");
// ^ Capital C ^ Missing `i`'s and `o`.
Old Answer
These 2 lines:
var groupcn = All,All,All,All;
var grpNameArr = abc,def,ghi;
Are probably your problem.
What you're doing there is assigning the variable All to a new variable groupcn, then declaring All as a new variable, 3 times.
var groupcn=All,
All, // new variable with the name `All`
All, // new variable with the name `All`
All; // new variable with the name `All`. These 3 override `All`
You'll need to initialize them like this:
var groupcn = [All,All,All,All];
var grpNameArr = [abc,def,ghi];
Other than that, assuming m is the length of groupcn, the code should work.
However, a shorter solution is to copy the arrays like this:
var contain = groupcn.slice();
var cmds = grpNameArr.slice();
Following mistakes were in the code
Using one loop for both the arrays. Since there length is not same two different loops should be used.
There was typo mistake in groupcn variable.
Check this code
<!DOCTYPE html>
<html>
<script>
function chk()
{
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(groupcn.length-1);ii++)
contain[ii] = groupcn[ii];
for(ii=0;ii<(grpNameArr.length-1);ii++)
cmds[ii] = grpNameArr[ii];
alert("groupcn = "+contain);
alert("grpNameArr = "+cmds);
}
</script>
<body onload="chk()">
</body>

WinJS: Efficient xml parsing

I currently have the bellow code to get some data from an xml feed.
var title = []
var start = []
var end = []
var xml = result;
var channel = xml.split('<channel')[1].split('>')[0].split('"')[1]
var xmlLength = xml.split("<programme>").length - 1;
for (var i = 0; i < xmlLength; i++) {
var event = xml.split("<event>")[i + 1].split("</event>")[0];
title[i] = programme.split("<title>")[1].split("</title>")[0];
var rs = programme.split("<start>")[1].split("</start>")[0].split(/\-|\s/);
var re = programme.split("<end>")[1].split("</end>")[0].split(/\-|\s/);
start[i] = new Date(rs.slice(0, 3).join('/') + ' ' + rs[3]);
end[i] = new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
setListView(event, start, end, channel)
This currently works but it doesn't seem very efficient. I wonder if there is a better way of doing it.
Well, it looks like you should be using the classes in the Windows.Web.Syndication namespace as it looks like you are doing RSS related things, but you could also use the raw XML API's as well.
It seems like you are trying to parse the XML on your own. Have you considered using jQuery.parseXML()?
Check it out here: http://api.jquery.com/jQuery.parseXML/

Categories

Resources