views:

93

answers:

3

I need a regular expression in javascript which does the following.

Those instances of a which are not the part of an HTML entity, should be replaced with w.

Ex:

abc should change to wbc

aabacaa should change to wwbwcww

&abcaa& should change to &wbcww&  

and so on.

I am using JavaScript.

Any help is appreciated.

A: 

a non-regex way, in your favourite programming language, split your string on "&a" (or &), replace the splitted items , then join back eg in Python

>>> s="&abcaa&"
>>> '&a'.join( [ i.replace("a","w") for i in  s.split("&a") ] )
'&wbcww&'
ghostdog74
+5  A: 

Try this:

"&abcaa&".replace(/&[^;]+;|a/g, function($0) {
    return $0 === "a" ? "w" : $0;
})
Gumbo
Neat! I really should learn JavaScript.
Bart Kiers
Varun
@Varun: Yes it will.
Tim Down
@Varun: `replace` is not a mutator method. That means the original string the method is used on stays untouched. You need to assign the return value of `replace` to your variable if you want to change its value: `str = str.repalce(/* … */)`.
Gumbo
A: 

As a more general answer, when writing regular expressions, the first thing I do is to go to http://rubular.com and lay out a couple of test strings. I then write and re-work the regular expression until it does what I need.

Yes, I know Rubular is a Ruby regex site, but RegExp syntax is very similar, if not identical for most languages (I think Perl uses an extended syntax). I've successfully used Rubular to test Java RegExps.

Matthias