views:

42

answers:

1

Hey all;

I'm trying to wrap all occurrences of an IP address with an HREF so I can then Do Stuff(tm).

I've run the regex itself through several validators, and it matches pattern as expected. Therefore, I'm thinking my problem is in the implementation, but I can't see the correct path. Can anyone help out?

Here's the regex and relevant code:

var theIps = new RegExp('^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$','g');  
var newBody = jQuery('#ELEMENT').html();  
var processed = newBody.replace(theIps, '<a class="ipPopup" href="javascript:void(0)" rel="10.5.1.2"    onclick="addToWatchlist(this)">TESTING REGEX</a>');  
jQuery('#ELEMENT').html(processed);

Thanks in advance for any assistance...

+1  A: 

Use regex syntax for your regex:

var theIps = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/g;  

When you build the RegExp object from a string, you have to double the backslashes. If the regular expression is constant (i.e., you're not building it up dynamically) then it's easier to use the "native" syntax.

Pointy
I just edited out the `new` before the regex - sorry.
Pointy
Thanks for your prompt reply -- and for fixing my post :-)
TRB
Grrr enter submits...now I know that. So I made the change you suggested (firefox was complaining before I removed the 'new', now resolved), but I still get the same output as before, no substitution having taken place. Does replace not work the way I think it does, or is there anything you can see in this code that would explain it? Thanks again!
TRB
Well the regex itself seems to work, at least basically. Are you sure you've got a container with the "id" value "ELEMENT"? Have you tried doing it with just `jQuery('body')`?
Pointy
Yes, I even abstracted the relevant stuff to its own file just to get it working, and alert the result instead of trying to pipe it back into the DIV -- still no substitution takes place. At this point I'm thinking there's something very basic I'm missing, but having looked at it as long as I have keeps the solution elusive.
TRB
Oh, duhh - sorry about that but I just saw the problem. You've got `^` and `$` anchors around the regex, so it'll only match when the entire string is an IP address! Just get rid of those and make sure you've got the `g` flag at the end of the regex and it should work.
Pointy
If you want to avoid having it match something like 20200100201.2.2.2 then you can put `\b` at the start and end of the pattern. That matches word boundaries, which usually does what you want.
Pointy
That was it -- you are the man! Thank you so much for sticking with me through it.
TRB