3

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.

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.