<html><head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>foo</title> <script type="text/javascript" charset="utf-8"> function parse(string) { var hasSubQuery = false; var hasAs = false; // first do a non-specific sweep to get a chunk of text to process var pattern = /select\s(.+)\sfrom/i; var re = new RegExp(pattern); var matches = re.exec(string); var pieces = matches[1].split(','); var out = new Array(); for (var i=0; i < pieces.length; i++) { tmp = pieces[i].replace(/^\s+/g, ""); // trim front of string out[i] = tmp.replace(/\s+$/g, ""); // trim end of string // check for presence of subquery and AS sql keyword if (out[i].indexOf('(') != -1) { pattern = /\)\s+(\w+)\s*$/i; if (matches[1].toLowerCase().indexOf('as') != -1) { pattern = /\s+AS\s+(\w+)$/i; } re = new RegExp(pattern); matches = re.exec(out[i]); out[i] = matches[1]; } } console.log(out); return out; } </script></head><body id="" onload=""> <h1>Regex test</h1> <textarea id="textarea"></textarea> <button onclick="parse(document.getElementById('textarea').value)" value="parse"> parse </button></body></html>