Link to home
Start Free TrialLog in
Avatar of mattjp88
mattjp88Flag for United States of America

asked on

use variable in regexp

So I have a working regular expression that does what I want.  The problem is that I need to insert a variable into the regexp.  The code is attached.  How do I get the second code snippet to work.
WORKS
<script type="text/javascript">
  var re = /(\b)(glossary term)(?![^<]*>|[^<]*<\/a>)/g;
  var sourcestring = 'aglossary term <a href="page.aspx">glossary term</a> glossary term <test glossary term test> glossary term';
  var replacementpattern = '$1<a href="glossary.aspx#$2" title="def" class="glossary">$2</a>';
  var result = sourcestring.replace(re, replacementpattern);
  alert("result = " + result);
</script>
 
DOES NOT WORK
<script type="text/javascript">
  var word="glossary term";
  var re = new RegExp("(\b)("+word+")(?![^<]*>|[^<]*<\/a>)","g");
  var sourcestring = 'aglossary term <a href="page.aspx">glossary term</a> glossary term <test glossary term test> glossary term';
  var replacementpattern = '$1<a href="glossary.aspx#$2" title="def" class="glossary">$2</a>';
  var result = sourcestring.replace(re, replacementpattern);
  alert("result = " + result);
</script>

Open in new window

Avatar of hielo
hielo
Flag of Wallis and Futuna image

Try:
var re = new RegExp("(\\b)("+word+")(?![^<]*>|[^<]*<\\/a>)","g");

Open in new window

Avatar of mattjp88

ASKER

no dice
What part is not working. Both seem to be alerting the same value
in FF 3 it alerts 2 different values
<script type="text/javascript">
  var re = /(\b)(glossary term)(?![^<]*>|[^<]*<\/a>)/g;
  var sourcestring = 'aglossary term <a href="page.aspx">glossary term</a> glossary term <test glossary term test> glossary term';
  var replacementpattern = '$1<a href="glossary.aspx#$2" title="def" class="glossary">$2</a>';
  var result = sourcestring.replace(re, replacementpattern);
  alert("result = " + result);
</script>
 
<script type="text/javascript">
  var word="glossary term";
  var re = new RegExp("(\b)("+word+")(?![^<]*>|[^<]*<\/a>)","g");
  var sourcestring = 'aglossary term <a href="page.aspx">glossary term</a> glossary term <test glossary term test> glossary term';
  var replacementpattern = '$1<a href="glossary.aspx#$2" title="def" class="glossary">$2</a>';
  var result = sourcestring.replace(re, replacementpattern);
  alert("result = " + result);
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Don't know what I did before, but your code works.  Thanks!!
You are welcome!