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..
 
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'
 
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..
 
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