I’m trying to construct a javascript function to replace one classname with another one. When I use a function like
function foo(bar)
{
bar.className=bar.className.replace(/\bone/, "two");
}
on a markup like
<div class="one" onclick="foo(this)"></div>
it correctly finds and replaces one with two. But when I’m using brackets to include other characters which may precede one, \b fails to recognize the beginning of the string, and gives no matches. Example:
function foo(bar)
{
bar.className=bar.className.replace(/[\b\s]one/, "two");
}
doesn’t work. Not even /[\b]one/ will work.
See http://jsfiddle.net/E4ph5/ to see it in action. What am I doing wrong? (In the fiddle, if you remove the brackets, the script works correctly.)
Brackets define a character class. Inside such a class markers such as
\b(word boundary) do not work as they do not make sense there./\bone/is fine in your case anyway – whitespace is also a word boundary: http://jsfiddle.net/ThiefMaster/Z8HTE/ – you could improve it by using/\bone\b/to avoid matching e.g.class="onetwothree"