Maryam
Maryam

Reputation: 1071

sql Query Parsing in javascript

I'm trying to create a javascript function that extract columns names, tables names and where conditions from a string such as "Select col1 , col2 from table1 where x = "123a" ", I wrote the following code to extract the columns names only but the problem is when I execute it, the result is weird, its 1,2,3,4,5 ! can anyone atleast explain to me why I'm getting this weird result ?

<!DOCTYPE html>
<html>
<head></head>
<body>

<button onclick = "MyFunc()">Try</button>
<p id = "y"></p>

<script>
function MyFunc(){

var str = "select col1 , col2 from table1";
var res = str.split(" ");
var cols = [];
for (x in res)
{
if (x !== "select" && x !=="from")
cols.push(x);

}
document.getElementById("y").innerHTML=cols;
}
</script>

</body>
</html>

Upvotes: 0

Views: 2250

Answers (1)

Georgi Naumov
Georgi Naumov

Reputation: 4201

Hmmm.

You can check how this work (just paste it into browser console):

var columnNames = (/\bselect\b\s+([\S\s]+?)from/i.exec("select col1 , col2 from table1") || [,""])[1].split(/\s*,\s*/g);
console.log("This column names are: " + columnNames.join(","));

or create function:

function getColumnNames(input) {
    return (/\bselect\b\s+([\S\s]+?)from/i.exec(input) || [,""])[1].split(/\s*,\s*/g);
}

Upvotes: 2

Related Questions