Javascript regex in with special character in between - javascript

Hello can anyone help my about regex. this is the string
((11A1:I19 + 11A1:K19 + 11A1:L19 + 11A1:I20 + 11A1:K20) - (11A1:N19 + 11A1:N20))
and this is the regex
/([0-9a-z])\w+:\w+([0-9-a-z])/g
I want to take 11A1:I19, 11A1:K19, etc.. and replace it with values so the string will look like this (1767+154+1123 - (151-17)) This is the full code
$f.each(function() {
var formula = $(this).data("formula");
var formula = $f.data("formula");
formula.split(/([0-9a-z])\w+:\w+([0-9-a-z])/g)
.forEach(function(el) {
if (el) {
var hy = el.split(':');
let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();
formula = formula.replace(el, v);
}
});
console.log(formula)
var result = eval(formula);
$f.val(result)
});

I believe you want to do something like this (not tested with jquery)
$f.each(function() {
var formula = $(this).data("formula");
var formula = $f.data("formula");
formula.split(/([0-9a-z]+:[0-9a-z]+)/gi)
.forEach(function(el) {
if (el) {
var hy = el.split(':');
if (hy.length==2) {
let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();
formula = formula.replace(el, v);
}
}
});
console.log(formula)
var result = eval(formula);
$f.val(result)
});
Update: After some more thinking, this code is more compact and possibly easier to read:
$f.each(function() {
var formula = $(this).data("formula");
var formula = $f.data("formula");
var Re=/([0-9a-z]+):([0-9a-z]+)/gi;
var hy;
var replaced=formula;
while ((hy=Re.exec(formula))!=null) {
let v = $('[data-sheet="' + hy[1] + '"][data-cell="' + hy[2] + '"]').val();
replaced = replaced.replace(hy[0], v);
}
console.log(replaced)
var result = eval(replaced);
$f.val(result)
});
For safety reasons, I would also check that v is a valid number before replacing it in the formula. That will avoid evaluating some code that might be a valid javascript expression with dire consequences. You can test it with:
if (isNaN(v+0)) continue;
Add it before replacing hy[0] with v.

Related

How to retrieve values of translate3d?

This question has already been asked before on StackOverflow, what is different with mine is that I'd like to be able to retrieve negative values and also be able to retrieve it with another parameter in transform which would be rotateZ(...deg) in my case.
I've followed another post on how I can get values of translate3d, the suggested code works and it gets the positiv values but not negative ones (the minus sign is missing).
Another problem is that when I add a new paramater nothing works anymore, I'd like to be able to add whatever paramaters and still make it work.
I think this comes from an issue with the Regex, see http://jsfiddle.net/Lindow/3gBYB/81/
Regular expression :
transform.match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))\))/)
Javascript :
function getTransform(el) {
var transform = window.getComputedStyle(el, null).getPropertyValue('-webkit-transform');
var results = transform.match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))\))/);
if(!results) return [0, 0, 0];
if(results[1] == '3d') return results.slice(2,5);
results.push(0);
return results.slice(5, 8); // returns the [X,Y,Z,1] values
}
var slider = document.getElementById('slider');
var translation = getTransform(slider);
var translationX = translation[0];
var translationY = translation[1];
var absX = Math.abs(translationX);
var absY = Math.abs(translationY);
alert(absX + ' : ' + absY);
HTML/CSS :
<div id="slider"></div>
----
#slider {
-webkit-transform:translate3d(-393px, -504px, 0) rotateZ(30deg);
// remove rotateZ to make it work with positiv values
// number in translate3d may vary from -9999 to 9999
}
Any suggestions ?
I've adapted your JSFiddle answer to provide a solution - updated your regex to allow for negative numbers, and added a method, "rotate_degree", that will calculate the rotation angle from the computedStyle matrix. This value is placed as an integer at the end of the results array.
Solution is on JSFiddle here: http://jsfiddle.net/Lymelight/3gBYB/89/
function getTransform(el) {
var transform = window.getComputedStyle(el, null).getPropertyValue('-webkit-transform');
function rotate_degree(matrix) {
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else {
var angle = 0;
}
return (angle < 0) ? angle +=360 : angle;
}
var results = transform.match(/matrix(?:(3d)\(-{0,1}\d+\.?\d*(?:, -{0,1}\d+\.?\d*)*(?:, (-{0,1}\d+\.?\d*))(?:, (-{0,1}\d+\.?\d*))(?:, (-{0,1}\d+\.?\d*)), -{0,1}\d+\.?\d*\)|\(-{0,1}\d+\.?\d*(?:, -{0,1}\d+\.?\d*)*(?:, (-{0,1}\d+\.?\d*))(?:, (-{0,1}\d+\.?\d*))\))/);
var result = [0,0,0];
if(results){
if(results[1] == '3d'){
result = results.slice(2,5);
} else {
results.push(0);
result = results.slice(5, 9); // returns the [X,Y,Z,1] value;
}
result.push(rotate_degree(transform));
};
return result;
}
var slider = document.getElementById('slider');
var translation = getTransform(slider);
console.log(translation);
var translationX = translation[0];
var translationY = translation[1];
var absX = Math.abs(translationX);
var absY = Math.abs(translationY);
console.log('TrX: ' + translationX + ', TrY: ' + translationY + ' , Rotation Angle: ' + translation[3]);
alert('TrX: ' + translationX + ', TrY: ' + translationY + ' , Rotation Angle: ' + translation[3])
I've also found another solution,
for (HTML) :
<div style="translate3d(-393px, -504px, 0) rotateZ(30deg);">...</div>
do (JavaScript) :
// get translate3d(..px, ..px, 0px) rotateZ(30deg)
function matrixToArray(matrix) {
return matrix.substr(7, matrix.length - 8).split(', ');
}
function matrix_translate3d(pos) {
var matrix_list = [];
matrix = matrixToArray($(pos).css("-webkit-transform"));
x = matrix[4].replace(/px/gi, '');
y = matrix[5].replace(/px/gi, '');
matrix_list.push(parseInt(x));
matrix_list.push(parseInt(y));
return matrix_list;
}
var matrix_position = matrix_translate3d(...);
// matrix_position[0], matrix_position[1]
Short solution.

How to parse XML string with Prototype?

I have a string <ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul> and on client side I have to convert it to JSON. Something like {data:['Foo','Bar'],params:['100;50','200;150']}
I found a pretty good way to achieve it in here so my code should be something like that
var $input = $(input);
var data = "data:[";
var params = "params:[";
var first = true;
$input.find("li").each(function() {
if (!first) {
data += ",";
params += ",";
} else {
first = false;
}
data += "'" + $(this).text() + "'";
var e = $(this).attr("e");
var n = $(this).attr("n");
params += "'" + e + ';' + n + "'";
});
return "{data + "]," + params + "]}";
But the problem is that I can't use jquery. How can I do the same thing with prototype?
You want to use a DOM parser:
https://developer.mozilla.org/en/DOMParser
Something like this...
var xmlStr = '<ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul>';
var parser = new DOMParser();
var doc = parser.parseFromString(xmlStr, "application/xml");
var rootElement = doc.documentElement;
var children = rootElement.childNodes;
var jsonObj = {
data: [],
params: []
};
for (var i = 0; i < children.length; i++) {
// I realize this is not how your implementation is, but this should give
// you an idea of how to work on the DOM element
jsonObj.data.push( children[i].getAttribute('e') );
jsonObj.params.push( children[i].getAttribute('n') );
}
return jsonObj.toJSON();
Also, don't manually build your JSON string. Populate an object, then JSON-encode it.
Edit: Note that you need to test for DOMParser before you can use it. Check here for how you can do that. Sorry for the W3Schools link.
Why you are building an array object with string? Why not
var data = new Array();
var params = new Array();
$$("li").each(function() {
data.push ($(this).text());
params.psuh($(this).attr("e") + ";" + $(this).attr("n"));
});
return {data:data.toString(), params:params.toString()};
or
return {data:data, params:params};

Javascript, trying to get conversion average

I have a script that is setting conversion rates depending on input boxes (works fine), however I now want to get an average of these rates.
My Code is
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
The id conversion1,2 etc have a number from 0-100 (the conversion rate). However whenever I run this script I get all sorts of crazy numbers for the average (sumavg or id conversion7). I do not know why! I should also note that this bit of code is inside of the function doing the conversion for each day which works fine.
See below for entire snippet:
// Conversion Rate
$.fn.sumConv = function(customers) {
var sum = 0;
var val = 0
this.each(function() {
if ( $(this).is(':input') ) {
val = $(this).val();
} else {
val = $(this).text();
}
customersval = $(customers).val();
sum = (customersval/val) * 100;
//sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
sum = Math.round(sum*Math.pow(10,2))/Math.pow(10,2);
if(sum=="Infinity" || sum=="NaN") sum=0;
});
// do average
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
return sum;
};
$('input#foot1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#customers1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#foot2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#customers2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#foot3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#customers3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#foot4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#customers4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#foot5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#customers5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#foot6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
$('input#customers6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
I suppose you have to apply parseFloat to your data. text method returns string, not number. Take a look at the simple example:
var avg1 = "1";
var avg2 = "1";
var avg3 = "1";
var avg4 = "1";
var avg5 = "1";
var avg6 = "1";
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg will be 18518.5 and not 1.
Wrap all avg data with parseFloat:
var avgN = parseFloat($('#conversionN').text());
You're repeating a lot of code, so I advise employing a DRY technique to minimise that -- e.g. make a bindKeyUp function...
Anyway, you need numbers. .text() returns strings. E.g. "99" + "77" === "9977". This is where your crazy numbers might be coming from. Try this:
var avg1 = ~~$('#conversion1').text();
var avg2 = ~~$('#conversion2').text();
// repeat
~~ just converts its operand to a number (and floors it towards 0). More info.
Or, to make it clearer, use parseFloat:
var avg1 = parseFloat($('#conversion1').text());
var avg2 = parseFloat($('#conversion2').text());
// repeat

.read .write .replace string elements in jQuery

I have these 2 functions (serialize and deserialize) in Javascript (below) and I want to change it to jQuery. I am wondering what would the right replacement for read and write in jQuery. Read and write strings are from and to a Textarea. This is part of Openlayers vector formats, getting geometries into / from OL map canvas.
Serialize is outputing the geometries from mapcanvas to textarea.
function serialize(feature) {
var type = document.getElementById("formatType").value;
var pretty = document.getElementById("prettyPrint").checked;
var str = formats['out'][type].write(feature, pretty);
str = str.replace(/,/g, ', ');
document.getElementById('output').value = str;
}
Deserialize is reading string from Textarea into OL mapcanvas.
function deserialize() {
var element = document.getElementById('text');
var type = document.getElementById("formatType").value;
var features = formats['in'][type].read(element.value);
var bounds;
if(features) {
if(features.constructor != Array) {
features = [features];
}
for(var i=0; i<features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectors.addFeatures(features);
map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
element.value = features.length + ' feature' + plural + ' added';
} else {
element.value = 'Bad input ' + type;
}
}
Thanks in advance.
Again, I am asking about the read and write function equivalent in jQuery. These 2 lines:
var str = formats['out'][type].write(feature, pretty);
var features = formats['in'][type].read(element.value);
to get the text in a text area
$("#myTextArea").val();
To set it to something
$("#myTextArea").val("Foo bar.");

building a database string

I'm trying to build a database based on some arbitrary data on a website. It's complex and changes for each site so I'll spare the details. Here's basically what I'm trying to do
function level0(arg) { textarea.innerHTML += arg + ' = {'; }
function level1(arg) { textarea.innerHTML += '\n\t' + arg + ': ['; }
function level2(arg) { textarea.innerHTML += arg + ', '; }
And so on. The thing is some level1's don't have any children and I can't get the formatting right.
My three problems are as follows.
The ending commas are going to break in IE (thank you MS)
Empty level1's shouldn't be printed if they don't have any children
Closing /curly?brackets/
HERE'S A DEMO of what I have so far. Notice the ending commas, the empty sub2 which shouldn't be printed, and no closing brackets or braces
Do I need to redesign the entire thing?
Is there also a way to have this all in one function so I don't have to worry if I add another layer?
EDIT
This needs to be done in a string format, I can't build an object and then stringify it, mostly because I need to know which element I'm in the middle of adding to.
Overall it looks that you still might want to build an object, but in case you insist on not building it - here is some sample solution:
function Printer() {
var result = '',
lastLevel = null,
close = {0:'\n}', 1:']', 2:''},
delimiter = {0: ',\n', 1:',\n', 2:','};
function closeLevel(level, noDelimiter) {
if(lastLevel === null)
return;
var l = lastLevel, d = level == lastLevel;
while(l >= level) {
result += close[l] + (l == level && !noDelimiter ? delimiter[l]:'');
l--;
}
}
this.level0 = function(arg) {
closeLevel(0);
result += arg + ' = {\n';
lastLevel = 0;
};
this.level1 = function(arg) {
closeLevel(1);
result += '\t' + arg + ': [';
lastLevel = 1;
};
this.level2 = function(arg) {
closeLevel(2);
result += arg;
lastLevel = 2;
};
this.getResult = function() {
closeLevel(lastLevel, true);
return result;
}
}
var p = new Printer();
p.level0('head');
p.level1('sub1');
p.level2('item1');p.level2('item2');p.level2('item3');
p.level1('sub2');
p.level1('sub3');
p.level2('newthing');
p.level0('head2');
document.getElementById('textarea').value = p.getResult();
You could see it in action here.
I'm not sure why you're building what looks like objects with nested arrays, using string concatenation. Something like this would be much simpler, since it wouldn't require fixing trailing commas, etc:
Edit: I've updated the code to make it keep track of the last level put in.
function Db() {
var level0, level1;
var data = new Object();
this.level0 = function(arg) {
level0 = new Object();
data[arg] = level0;
}
this.level1 = function(arg) {
level1 = new Array();
level0[arg] = level1;
}
this.level2 = function(arg) {
level1.push(arg);
}
this.toString = function() {
var s = '';
for(i in data) {
s += i + '\n';
for(j in data[i]) {
if(data[i][j].length>0) {
s += '\t' + j + ': [' + data[i][j] + ']\n' ;
}
}
}
return s;
}
}
Use like this:
var db = new Db();
db.level0('head');
db.level1('sub1');
db.level2('item1');db.level2('item2');db.level2('item3');
I've tested this in the demo you linked and it works just fine.

Categories