Regex Replace doesn't obey $1 - javascript

var input = document.getElementById('textinput').value;
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
for(var iii=0; iii<=key; iii++) //for each line
{
var filenameRegex = /^\* \[\[Media:(.+?)(\|)/;
var results = lines[iii].match(filenameRegex);
var filename;
console.log('lines[iii]= '+lines[iii]);
if(results!==null && results.length!== 0)
{
output += lines[iii].replace(filenameRegex,'$1');
}
}
I try hard but the output is always output += lines[iii].replace(filenameRegex,'$1$2')
even though I only want $1
Example input: * [[Media:importantstuff|unimportantstuff]]
Expected output: importantstuff
Actual output: importantstuffunimportantstuff]]

If I understood you correctly, you are looking for this:
Demo
Code:
var filenameRegex = /^\* \[\[Media:(.+?)\|.*/;
var results = lines[iii].match(filenameRegex);
var filename;
console.log('lines[' + iii + ']= ' + lines[iii]);
console.log('key[' + iii + ']= ' + key);
if (results !== null && results.length !== 0) {
output += lines[iii].replace(filenameRegex, '$1');
}

Related

Check a json value against a regexp throws a is not a function error

I've a problem with an if statement, where I want to check the value against a regExp. But I get "data[key].name is not a function", how do I go about to fix this issue?
document.querySelector('#search').onkeyup = function() {
var searchField = document.querySelector('#search').value;
var myExp = new RegExp(searchField, "i");
var request = new XMLHttpRequest();
request.open('GET', 'allCountries.json', true);
request.onreadystatechange = function() {
if ((request.readyState === 4) && (request.status === 200)) {
var data = JSON.parse(request.responseText);
var output = '<ul class="searchresult">';
for(var key in data) {
if(data[key].name(myExp) != -1 || data[key].code(myExp) != -1) {
output += '<li>' + data[key].name + ' - ' + data[key].code +
'</li>';
}
}
output += '</ul>';
document.querySelector('#update').innerHTML = output;
}
};
request.send();
};
If you want to check if a String matches a RegEx pattern, use the String#match() function:
Change your if statement to
if (data[key].name.match(myExp) || data[key].code.match(myExp)) {
var myExp = new RegExp("something.*[23]", "i");
var data = {a:{name:"something1", code:"somethingElse1"}, b:{name:"something2", code:"somethingElse2"}, c:{name:"something3", code:"somethingElse3"}}
var output = '<ul class="searchresult">';
for (var key in data) {
if (data[key].name.match(myExp) || data[key].code.match(myExp)) {
output += '<li>' + data[key].name + ' - ' + data[key].code +
'</li>';
}
}
output += '</ul>';
document.querySelector('#update').innerHTML = output;
<div id="update"></div>
If name and code are strings you should test your regex this way:
if(myExp.test(data[key].name) || myExp.test(data[key].code))

Conversion of JSON to CSV using Javascript doesnt give Keys

I have converted JSON to CSV using JavaScript but in a bizarre fashion, I don't see the headers being transferred to CSV file. I only see the corresponding values.
Below is the example of
1) JSON ....
[
{
"entityid": 2,
"personid": 45676
}
]
2) JavaScript code ....
function DownloadJSON2CSV(objArray)
{
alert(objArray);
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
//line += array[i][index] + ',';
if (line != '') line += ','
line += array[i][index];
}
alert(line);
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
//line.slice(0,line.Length-1);
str += line + '\r\n';
}
alert(str);
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
3) CSV Output ....
2,45676
I should see the keys - entityid and personid also in CSV in the first line of the document, but I don't.
This code will extract headers from the json keys additionally it will double quote the fields which include commas in it.
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var keys = [];
for(var k in objArray[0]) keys.push(k);
for (var i = 0; i < keys.length; i++)
{
if(i==keys.length-1){str=str+keys[i]+'\r\n'}
else {str=str+keys[i]+','}
}
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
if(array[i][index].toString().includes(",") && typeof array[i][index] === 'string'){array[i][index]="\""+array[i][index]+"\""}
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
Usage: (for Node.js)
var fs = require('fs'); //**run** npm install fs **if not installed yet in cmd**
var arrayOfObjects = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"},{"id":89,"Title":"England"}];
fs.writeFile("./test.csv", convertToCSV(arrayOfObjects));
You hadn't set it up to output the header line.
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var headers = new Array();
for (var i = 0; i < array.length; i++) {
var line = '';
var data = array[i];
for (var index in data) {
headers.push(index);
if (line != '') {
line += ','
}
line += '"' + array[i][index] + '"';
console.log('line: ' + line);
}
str += line + ((array.length>1) ? '\r\n' : '');
line = '';
}
headers = ArrNoDupe(headers);
console.log('headers: ' + headers);
console.log('str: ' + str);
str = headers + '\r\n' + str;
console.log('final str: ' + str);
window.open( "data:text/csv;charset=utf-8," + escape(str));
}
function ArrNoDupe(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
CSV outputs like so...
entityid,personid
"2","45676"

Insert "and" before the last element jquery

var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
'&nbsp' + ':' + '&#160' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!

Using javascript to download file as a.csv file

I am trying to export a file as .csv file so that when the user clicks on the download button, the browser would automatically download the file as .csv.
I also want to be able to set a name for the .csv file to be exported
I am using javascript to do this
The code is below:
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
// Example
$(document).ready(function () {
// Create Object
var items = [
{ "name": "Item 1", "color": "Green", "size": "X-Large" },
{ "name": "Item 2", "color": "Green", "size": "X-Large" },
{ "name": "Item 3", "color": "Green", "size": "X-Large" }];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
$("#download").click(function() {
alert("2");
var csv = ConvertToCSV(jsonObject);
window.open("data:text/csv;charset=utf-8," + escape(csv))
///////
});
});
I have written a solution in this thread: How to set a file name using window.open
This is the simple solution:
$("#download_1").click(function() {
var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
var json = $.parseJSON(json_pre);
var csv = JSON2CSV(json);
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "data.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
JSON2CSV function:
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
if ($("#labels").is(':checked')) {
var head = array[0];
if ($("#quote").is(':checked')) {
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[0]) {
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for (var i = 0; i < array.length; i++) {
var line = '';
if ($("#quote").is(':checked')) {
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[i]) {
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return str;
}
in modern browsers there is a new attribute in anchors.
download
http://caniuse.com/download
so instead of using
window.open("data:text/csv;charset=utf-8," + escape(csv))
create a download link:
download
another solution is to use php
EDIT
i don't use jQuery, but you need to edit your code to add the download link
with something like that in your function.
var csv=ConvertToCSV(jsonObject),
a=document.createElement('a');
a.textContent='download';
a.download="myFileName.csv";
a.href='data:text/csv;charset=utf-8,'+escape(csv);
document.body.appendChild(a);
Try these Examples:
Example 1:
JsonArray = [{
"AccountNumber": "1234",
"AccountName": "abc",
"port": "All",
"source": "sg-a78c04f8"
}, {
"Account Number": "1234",
"Account Name": "abc",
"port": 22,
"source": "0.0.0.0/0",
}]
JsonFields = ["Account Number","Account Name","port","source"]
function JsonToCSV(){
var csvStr = JsonFields.join(",") + "\n";
JsonArray.forEach(element => {
AccountNumber = element.AccountNumber;
AccountName = element.AccountName;
port = element.port
source = element.source
csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n";
})
return csvStr;
}
You can download the csv file using the following code :
function downloadCSV(csvStr) {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
hiddenElement.target = '_blank';
hiddenElement.download = 'output.csv';
hiddenElement.click();
}
I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.
I use $.getJSON to pull json data from an external page, but if you have a basic array, you can just use that.
This uses Christian Landgren's code to create the csv data.
$(document).ready(function() {
var JSONData = $.getJSON("GetJsonData.php", function(data) {
var items = data;
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(items[0]);
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
csv = csv.join('\r\n');
//Download the file as CSV
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "DataDump.csv"; //Name the file here
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
});
Edit: It's worth noting that JSON.stringify will escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.
You can add .replace(/\\"/g, '""') to the end of JSON.stringify(row[fieldName], replacer) to display this properly in excel (this will replace \" with "" which is what excel prefers).
Full Line: JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""')
One-liner function for simple JSON with static titles
Assuming arr is JSON array, you can also replace the first string with comma separated titles end with \n
arr.reduce((acc, curr) => (`${acc}${Object.values(curr).join(",")}\n`), "")
Or with the window.open function mentioned before
window.open(`data:text/csv;charset=utf-8,${arr.reduce((acc, curr) => (`${acc}${Object.values(curr).join(",")}\n`), "")}`)
You should also consider escape the strings or replace the , to avoid extra cells
If your data comes from a SQL Database, all your lines should have the same structure, but if coming from a NoSQL Database you could have trouble using standard answers. I elaborated on above JSON2CSV for such a scenario.
Json data example
[ {"meal":2387,"food":"beaf"},
{"meal":2387,"food":"apple","peeled":"yes", "speed":"fast" },
{"meal":2387,"food":"pear", "speed":"slow", "peeled":"yes" } ]
Answer
"meal","food","peeled","speed"
"2387","beaf","",""
"2387","apple","yes","fast"
"2387","pear","yes","slow"
Code for headers and double quotes for simplicity.
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
// get all distinct keys
let titles = [];
for (var i = 0; i < array.length; i++) {
let obj = array[i];
Object.entries(obj).forEach(([key,value])=>{
//console.log('key=', key, " val=", value );
if (titles.includes(key) ) {
// console.log (key , 'exists');
null;
}
else {
titles.push(key);
}
})
}
let htext = '"' + titles.join('","') + '"';
console.log('header:', htext);
// add to str
str += htext + '\r\n';
//
// lines
for (var i = 0; i < array.length; i++) {
var line = '';
// get values by header order
for (var j = 0; j < titles.length; j++) {
// match keys with current header
let obj = array[i];
let keyfound = 0;
// each key/value pair
Object.entries(obj).forEach(([key,value])=>{
if (key == titles[j]) {
// console.log('equal tit=', titles[j] , ' e key ', key ); // matched key with header
line += ',"' + value + '"';
keyfound = 1;
return false;
}
})
if (keyfound == 0) {
line += ',"' + '"'; // add null value for this key
} // end loop of header values
}
str += line.slice(1) + '\r\n';
}
return str;
}

Issue with multidimensional array

I am having an issue with this darn array. It was to post my info looking like this. Any ideas how to fix this?
prdpr=10.95^TBCC9^2^Shoes
prdsku=2.50^TDxa2^1^Pants
prdqn=7.50^Tasds^1^Hats
prdcatid=undefined^undefined^undefined^undefined
What it should look like is:
prdpr=10.95^2.50^7.50
prdsku=TBCC9^TDxa2^Tasds
prdqn=2^1^1
prdcatid=Shoes^Pants^Hats
Later I'll just string together for a URL
var advid = "xxx";
var oid = "xxx";
var amt = "20.95";
// This array I cannot mess with, this is just an example
var OrderDetails = new Array();
OrderDetails[0] = ['10.95','2.50','7.50'];
OrderDetails[1] = ['TBCC9','TDxa2','Tasds'];
OrderDetails[2] = ['2','1','1'];
OrderDetails[3] = ['Shoes','Pants','Hats'];
var prdpr = '';
var prdsku = '';
var prdqn = '';
var prdcatid = '';
for(var x = 0; x < OrderDetails.length; x++) {
var delim = "";
if(x == 0){
delim = "";
} else{
delim = "^";
}
prdsku += delim + OrderDetails[x][0];
prdpr += delim + OrderDetails[x][1];
prdqn += delim + OrderDetails[x][2];
prdcatid += delim + OrderDetails[x][3];
}
var output = '<div>Product Sku=' + prdsku + 'Item Cost=' + prdpr + 'Quanty=' + prdqn + 'Category=' + prdcatid + '</div>';
document.write(output);
var OrderDetails = new Array();
OrderDetails[0] = ['10.95','2.50','7.50'];
OrderDetails[1] = ['TBCC9','TDxa2','Tasds'];
OrderDetails[2] = ['2','1','1'];
OrderDetails[3] = ['Shoes','Pants','Hats'];
var delim = '^';
var prdpr = OrderDetails[0].join(delim);
var prdsku = OrderDetails[1].join(delim);
var prdqn = OrderDetails[2].join(delim);
var prdcatid = OrderDetails[3].join(delim);

Categories

Resources