regular expression

Associate
Joined
30 Dec 2005
Posts
415
Hi all,

I've got a simple regular expression in JavaScript but I can't get it working. I'm simply trying to search a string for words that match a certain format, and then replace them with a bit of code.

For example, it'd search this string..
Code:
The :fox jumped over the :gate into the field
and replace it with
Code:
The "+$('fox').val()+" jumped over the "+$('gate').val()+" into the field

All I have for the regular expression so far is ":[a-zA-Z] ", and that doesn't seem to work. If anyone could give me some pointers it'd be appreciated..
 
Soldato
Joined
12 Apr 2004
Posts
11,788
Location
Somewhere
You need to quantify your character class with a +, which tells it to take as many matches for the preceding group as possible. You can also omit the capitals in your character class by putting the i modifier on the end of the expression, which tells it to ignore case. Try this:

Code:
/:[a-z]+/i
 
Associate
OP
Joined
30 Dec 2005
Posts
415
Fantastic, thanks! I've just tried using that reg expr and it does seem to work, but it only seems to replace the first match...

Code:
var str = 'The :fox jumped over the :gate into the field';
var re = new RegExp(/:[a-z]+/i);
var m = str.replace(re,'cow');
alert(m); //outputs 'The cow jumped over the :gate into the field'
 
Associate
OP
Joined
30 Dec 2005
Posts
415
Almost there!

Code:
var str = 'The :fox jumped over the :gate into the field';
var re = new RegExp(/:[a-z]+/ig);
var m = str.replace(re,"'+ $('#$&').val()+'");
alert(m);

I just need to work out how to remove the : from the output.. in PHP I would have used preg_replace_callback to remove the colon, but there doesn't seem to be this sort of functionality in javascript..
 
Associate
OP
Joined
30 Dec 2005
Posts
415
Sorted :D

Code:
var str = 'The :fox jumped over the :gate into the field';
var re = new RegExp(/:\w+/igm);
var m = str.replace(re,function(mo,key,value) {
return "'+$('#"+mo.substr(1)+"').val()+'"
});
alert(m);

Cheers guys!
 
Back
Top Bottom