views:

561

answers:

2

We have a database where every table name starts with WW. I want to display an SQL on a web page, but wrap each table name with a link. For example:

"select * from wwx_something where ..."

Should be transformed into:

"select * from <a href='/table/wwx_something/'>wwx_something</a> where ..."

There might be several tables, of course, and it should not be case-sensitive.

I need a javascript regex solution...I can't seem to get it to work.

A: 

for simple regexes like this a tool called txt2re is pretty good. atleast to get you started.

it gives you the output:

var txt='select * from wwx_something where';

      var re1='.*?';    // Non-greedy match on filler
      var re2='(from)'; // Word 1
      var re3='(\\s+)'; // White Space 1
      var re4='((?:[a-z][a-z0-9_]*))';  // Variable Name 1
      var re5='(\\s+)'; // White Space 2
      var re6='((?:[a-z][a-z]+))';  // Word 2

      var p = new RegExp(re1+re2+re3+re4+re5+re6,["i"]);
      var m = p.exec(txt);
      if (m != null)
      {
          var word1=m[1];
          var ws1=m[2];
          var var1=m[3];
          var ws2=m[4];
          var word2=m[5];
          document.write("("+word1.replace(/</,"&lt;")+")"+"("+ws1.replace(/</,"&lt;")+")"+"("+var1.replace(/</,"&lt;")+")"+"("+ws2.replace(/</,"&lt;")+")"+"("+word2.replace(/</,"&lt;")+")"+"\n");
      }
mkoryak
thanks, but that's too complicated...i want to keep it simple...like match all "words" that start with "ww"...also I don't need the "%lt;" stuff because I want to create links, not display the HTML
Nick Perkins
A: 

Solution using a single replace:

var re = /(FROM|JOIN)\s+(WW\S+)/gi;
yourText.replace(re, "$1 <a href='$2'>$2</a>");

note that I also tentative support for stuff such like "SELECT * FROM wwa JOIN wwb".

ADDED after comment: yes, you can replace with a custom function in order to uppercase the URL:

var re = /(FROM|JOIN)\s+(WW\S+)/gi;
function change(s, p1, p2) {
    return p1 + " <a href='http://whatever/" + p2.toUpperCase() + "'>" + p2 + "</a>";
}
yourText.replace(re, change);

PS: IMHO it's better to include FROM/JOIN in the match because this way you're better warded about strays "ww" that have nothing to do with table names... including a bit of context always helps disambiguate.

lapo
Yes, this is more like it! ( but I only need one group, I don't need to match the (FROM|JOIN) ).( I was not using "$1" in my replacement string because I thought I needed "\1" )One more thing....can I convert one of the $1 to lower-case? (the one in the generated URL )
Nick Perkins