Forum Moderators: open

Message Too Old, No Replies

Regular expression for replacing fucntion

small problem

         

prasanth

5:43 am on Jun 29, 2005 (gmt 0)

10+ Year Member



Hi,
I have a function which highlights the key words selceted in the body. I calling replace function with regular expression

var rg=new RegExp(expr,"gi");

var endresult = contentString.replace(rg,function(thematch){
return '<span style="color:black;background-color:yellow">'+thematch+'</span>' ; } );

The problem with the code is , it is replacing even substrings but i want to replace only stings(i.e only if it is a full word). can any knows it please help.

RonPK

1:29 pm on Jun 29, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'll have make the regexp search for word boundaries ( \b ). Example:

var foo = 'Javascript is not Java';
var pat = /\b(java)\b/gi;
foo.replace(pat, "<b>$1</b>");

foo will now read 'Javascript is not <b>Java</b>'.

prasanth

5:33 am on Jun 30, 2005 (gmt 0)

10+ Year Member



Thanks for help,
I got that one but the search content for me is a variable of multistrings

e.g iit is like

var test =first¦income¦deposit;

I am defining variable like

var rg = new RegExp(test, "gi")

can i use some thing like new RegExp(test,"\b\b/gi")

or how it will be

thanks for the help again

RonPK

9:56 am on Jun 30, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



> can i use something like

How about some good old trial and error... ;)

This will probably be better:

var test ='\b(first¦income¦deposit)\b'; // solid pipes, of course