Javascript regular expressions for Query Builder - javascript

This may have been asked in the past but I couldnt find a suitable answer. What I am looking for is a method to extract parameters from an sql query such as below. The queries will always be an EXEC statement followed by the query name, and possible parameters.
Here is an example of what I may recieve
EXEC [dbo].[myProcedure] #Param1
This could also be as follows
EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3
Those are the only types of queries that the input will take. As for why I am doing this, well thats another question all together, and I am pretty set on going down this route.
What I am looking for is to be able to take the above strings and produce an array of values such as
['#Param1','#Param2','#Param3',....]
I originally tried to just parese using a simple while statement but I seem to have huge issues there.
I hope this question makes sense,
Cheers,
Nico
[Edit]
Sorted this by using the following statement
function eParams(e) {
var i = e.indexOf('#');
if (i <= 0)
return;
e = e.substring(i);
var p = e.split(',');
var eList = [];
var s = '';
for (var i = 0, j = p.length - 1; i <= j; i++) {
var sP = p[i].trim();
if (sP.indexOf('#') < 0)
continue;
eList.push(sP);
}
}

var str = 'EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3';
(str).match(/(#[^\s,]+)/g);
will return an array.

var s = "EXEC [dbo].[myProcedure] #Param1, #Param2, #Param3";
var i = s.indexOf('#');
var a = s.substr(i).split(/\s*,\s*/);
(error checking omitted)

Related

conditional splitting of string and word by matching characters in js

I have very long string that contains html as a string , numbers , my special bindings and numbers I want to split my bindings and sentences with spaces separately but my program is separately my bindings and words .
my js code:-
var x = 'hey this is {{name}} and I love to {{write}} and to learn as
much as I can. Now I am trying to separate sentences and my bindings'
var c = x.match(/\s*\S*\s*/g) // this splits words from string including
space
var mt = x.match(/{(.*)}/g); // trying to take out bindings but this don't
work
mt.forEach(function(a){ // taking each bindings separately
var z = x.match(a)
})
console.log(mt)
Somthing like this .. but I know this is totally wrong please help me
I don't have any idea :-
output that I am expecting:-
(5) ["hey this is", "i", "{{name}}", " and I love to ", "{{write}}", " and to learn as ↵ much as I can. Now I am trying to separate sentences and my bindings"]
How can i do this?
Please don't use jquery
Try this:
I've commented my code hoping it would make it easier to read. But do note that this code is far from perfect although it solves your problem.
var rawString = 'hey this is {{name}} and I love to {{write}} and to learn as much as I can. Now I am trying to separate sentences and my bindings';
var arrayRawString = rawString.match(/\s*\S*\s*/g); // this splits words from string including space
var arrayPlaceholder = rawString.match(/{(.\S*)}+/g); // trying to take out bindings but this don't work
// to store the final output
var separedArray = [];
// keeping track of the index to stich the array up
var posStart = 0;
var posEnd = 0;
arrayPlaceholder.forEach(function(arg){ // taking each bindings separately
// length of the array that holds placeholder (bindings)
var arsLength = arrayRawString.length;
for(var i = 0; i < arsLength; ++i) {
// if the provided text matches the original array's element
if(arrayRawString[i].match(arg)){
// to store the index
posEnd = arrayRawString.indexOf(arrayRawString[i]);
// join the pieces together upto the index defined
var res = arrayRawString.slice(posStart, posEnd).join('');
// to indicate whether the stored string is the placeholder
var flag = true;
// store the string obtained
separedArray.push(res.replace(arrayPlaceholder[(arrayPlaceholder.indexOf(arg) - 1) < 0 ? 0 : arrayPlaceholder.indexOf(arg) - 1 ], ''));
// check if the string still has placeholder (bindings)
// to remove it
for(var j = 0; j < arg.length; ++j) {
if(res[j] !== arg[j]) {
flag = !flag;
}
}
if ( flag ) {
separedArray.push(arg);
}
// last end position is the start position for next round
posStart = posEnd;
// because the loop runs only arrayPlaceholder.length times
// it solves the problem of last part not getting pushed to the final array
if( arrayPlaceholder[arrayPlaceholder.length-1] === arg ) {
res = arrayRawString.slice(posStart, arrayRawString.length).join('');
separedArray.push(res.replace(arg, ''));
}
}
}
});
console.log(separedArray);

Getting error .append is not a function

I am trying to split up a string on /* and then to split up those segments on */
So that I can separate out all of the comments as I want this code to be able to take all of the comments out of the string and then put it back together.
The problem is though I keep getting this .append error which I am pretty sure is because I have made a silly syntax error but I am struggling to find it and any help would be greatly appreciated.
JS
contents = "if for /* else */ . = == === /* return */ function"
var start = /\/\*/gi;
var end = /\*\//gi;
var commentsRemovedSec2 = [];
var commentsRemovedSec1 = contents.split(start);
console.log(commentsRemovedSec1);
for (var i = 0; i < commentsRemovedSec1.length; i++) {
var z = ""
var x = commentsRemovedSec1[i]
var y = x.split(start)
z = y[0]
commentsRemovedSec2.append(z);
};
console.log(commentsRemovedSec2);
Unfortunately .append() isn't an Array method.
Instead use the Array method .push().
commentsRemovedSec2.push(z)
The push() method adds one or more elements to the end of an array and
returns the new length of the array. MDN

Javascript / DOM, parsing Key/Value string

I send a string from a server to the Firefox Browser in the format below:
"KEY:a1 VAL:123.45"
And this string can contain many such records.
Here is the code I have written:
var e;
var reply = request.responseText;
var txt = "", tab, key = "", val = "";
var x = reply.getElementsByTagName("KEY:");
for(i = 0; i < x.length; i++)
{
txt = x[i].childNodes[0].nodeValue; // "KEY:%c%c VAL:%.2F"
tab = txt.split(":");
key = "table_" + tab[1].substring(0,1);
val = tab[2];
e = document.getElementById(key);
e.innerHTML = val;
e.style.display = "block";
}
val displays "KEY:a1 VAL:123.45" instead of the expected "123.45" (and of course the key variable is also wrong, not matching a table cell, just picking the first one in the table).
I don't even know how to display the key and val values (document.write() and alert() do nothing and I don't see how to trace this code in Firefox).
Any idea, tip, correction, or code example is welcome but please don't recommend using any library, I want to do it with little code.
EDIT: from the two comments, I understand that there are two distinct ways to proceed: either using DOM objects and HTML tags, or using 'strings'. I would prefer to keep using the format above, so please guide me to a 'string' solution. Thanks!
You can use a simple regular expression to extract the information from the string:
var value = "KEY:a1 VAL:123.45"​,
pattern = /KEY:(\S+) VAL:(.+)$/g;
var result = pattern.exec(value);
// result[1] == 'a1'
// result[2] == '123.45'
In your case, you'd use request.responseText instead of value.

Input type values into variables

Im trying to define variable values from values inputted into an input textfield onkeyup. I've never done this before and cant find it on Google so was wondering if anybody had any idea on how to do this...
<input type="text" id="values" />
var numberone = "";
var numbertwo = "";
var numberthree = "";
Imagine the user types into the input box "thomas the tankengine" thomas would become 'var numberone'. 'the' would become number two and so on...
Is this possible?
You can split a string by spaces using the split() function
eg
var words = document.getElementById("values").value.split(' ');
var op1 = words[0];
...
Possible, but unwise and would require messing about with eval if you didn't want the variables to end up in the global scope.
Any time you variable variables can solve a problem, it can be better solved by using an array (for sequential data) or object (for named data).
This is exactly the sort of job that arrays are designed to handle.
var numbers = document.getElementById('values').value.split(' ');
console.log(numbers[0]);
console.log(numbers[1]);
console.log(numbers[2]);
How about saving each word in an index of an array so you can have a dynamic number of words:
var max_words = 3;
$('#values').on('keydown', function (event) {
if (event.keyCode == 32) {//32 == space key
var arr = $(this).val().split(' '),
len = max_words < arr.length ? max_words : arr.length,
out = [];
for (var i = 0; i < len; i++) {
out.push(arr[i]);
}
}
});
Here is a jsfiddle to demonstrate this code: http://jsfiddle.net/r8dXw/1/ (Note that the output is logged via console.log so check your console to see the output)

Parse values out of paramaterized strings in javascript

Say I have a string, such as:
var map = "/directory/:id/thumbnails/:size";
And I want to use that to map against another string (essentially, the same thing that Rails uses to define Routes), such as:
var str = "/directory/10/thumbnails/large";
I would like to "compare" the two strings, and return a Key-Value Pair or JSON Object that represents the parts of str that map to map, which in my example above, would look like:
obj = {
'id' : '10',
'size' : 'large'
}
Would this be a good fit for JavaScript Regex? Can anyone help me?
I found it easier to just write the code for this than to explain :)
var map = "/directory/:id/thumbnails/:size";
var str = "/directory/10/thumbnails/large";
var obj = {};
var mapArr = map.split('/');
var strArr = str.split('/');
if (mapArr.length != strArr.length) return false;
for (var i = 0; i < mapArr.length; i++)
{
var m = mapArr[i];
var s = strArr[i];
if (m.indexOf(":") != 0) continue;
m = m.substring(1);
obj[m] = s;
document.write(m + " = ");
document.write(obj[m]);
document.write("<br/>");
}
You can also see it in action here => http://jsfiddle.net/5qFkb/
Do ask if you have any questions, but the code should be self-explanatory. Also be aware that there is no usual null checking and stuff I'd usually put in - this is just meant as a quick and dirty proof of concept.
Oh and in case it wasn't clear from my answer; no, I wouldn't use regex, because then I'd have two problems instead of one.

Categories

Resources