mattjp88
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>
ASKER
no dice
What part is not working. Both seem to be alerting the same value
ASKER
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>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Don't know what I did before, but your code works. Thanks!!
You are welcome!
Open in new window