Anat said:
I want to take a given string, and make certain words hyperlinks.
For example:
"Hello world, this is a wonderful day!"
I'd like the words world, wonderful and day to be hyperlinks, therefore
after my manipulation it should be:
"Hello <a href=...>world</a>, this is a <a href=...>wonderful</a> <a
href=...>day</a>!"
Using split method is not good, because the whitespaces, commas and
other punctuation marks are gone.
[...]
Any ideas on how I can locate words, replace them but not loose
punctuation marks on the way?
From your use of the `a' element, I assume this is for `innerHTML'.
Please note that this property is proprietary, and its behavior is
both implementation-dependent and context-dependent.
You could use \b of course, but that will get you in trouble with
words containing non-ASCII characters. Therefore:
var s = ...innerHTML;
s = s.replace(
/(^|[\s-])(world|wonderful|day)([\s,;.?!-]|$)/g,
"$1<a href="
http://en.wikipedia.org/wiki/$2">$2<\/a>$3");
...innerHTML = s;
Or with positive lookahead (requires JavaScript 1.5, JScript 5.5,
ECMAScript Ed. 3 [1]):
...
s = s.replace(
/([\s-]|^)(world|wonderful|day)(?=([\s,;.?!-]|$))/g,
'$1<a href="
http://en.wikipedia.org/wiki/$2">$2<\/a>');
...
(Use those character classes, unless you want to code all UCS
[non-]word characters as compactly defined in the XML grammar.)
I can remember to have suggested a probably more sophisticated replacing
approach a few months ago already, that also points out the difficulties
with general replacing. Search the (Google Groups) archives for "IBM
replace author

ointedEars" or so.
When implementing this, you should additionally take into account that too
many hyperlinks in continuous text can make that text hardly legible.
You are welcome. But please get your Exclamation Mark key repaired.
PointedEars
___________
[1] <URL:
http://pointedears.de/es-matrix>