Need Javascript Regex Replace to wrap certains words with <a ...>
We have a database where each table name starts with WW. I want to display SQL in a webpage, but wrap each table name with a link. For example:
"select * from wwx_something where ..."
Should be converted to:
"select * from <a href='/table/wwx_something/'>wwx_something</a> where ..."
Of course, there can be multiple tables and it doesn't have to be case sensitive.
I need a javascript regex solution ... I can't seem to get it to work.
+2
source to share
1 answer
Solution using one replace :
var re = /(FROM|JOIN)\s+(WW\S+)/gi;
yourText.replace(re, "$1 <a href='$2'>$2</a>");
Note that I am also tentatively supporting things like "SELECT * FROM wwa JOIN wwb".
ADDED after comment: yes, you can replace a custom function to make the URL shorthand:
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 is better to include FROM / JOIN in the match, because this way you are better protected from "ww" strikes that have nothing to do with table names ... including a little context always helps to fix the problem.
+2
source to share