On Jul 15, 8:45 am, Jeff <jeff@spam_me_n ot.comwrote:
Joost Diepenmaat wrote:
Joost Diepenmaat <jo...@zeekat.n lwrites:
myDiv.className .replace(/\bsome_other_cl ass\b/,"something_els e");
That should ofcourse be:
myDiv.className = myDiv.className .replace(/\bsome_other_cl ass\b/,"something_els e");
Perfect!
No, it's not. The class attribute value delimiter is one or more
whitespace characters, so a pattern should be used that matches that.
\b matches a word break which includes whitespace, but there are
characters that a javascript regexp recognises as a word break that
are not designated as class attribute value delimiters, such as hyphen
(-) and period (.). A better match is (^|\s)some_clas s(\s|$).
That will also remove some or all of the whitespace around the value
when replacing it, so pad the replacement string with spaces:
myDiv.className =
myDiv.className .replace(/(^|\s+)some_cla ss(\s+|$)/,"
something_else ");
Extra whitespace may now be inserted in the class attribute that some
browsers will not automatically trim. If you want, you can follow it
up with a trimming function that removes leading and trailing
whitespace, the \s+ should ensure there is no extra internal
whitespace.
The additional whitespace shouldn't be an issue unless you are doing
lots (hundreds?) of replacements for a particular element without re-
loading the page, however I think it is better to deal with it from
the start, so append:
.replace(/^\s+|\s+$/g,'')
or whatever your favourite trimming pattern is.
--
Rob