Page 1 of 1
[SOLVED] JavaScript: VAR inside a reg_exp
Posted: Sat Oct 02, 2004 5:44 am
by Calimero
This is the situation:
Code is on the page that collects input from the FORM
Code: Select all
Function abc ()
{
i_vars = new Array ("<? echo $var1 ?>", "<? echo $var1 ?>", "<? echo $var1 ?>");
for ( var i = 0; i < i_vars.length; i++)
{ var pattern = "/i_varsїi]/gi";
alert (i_varsїi]); // just to check taht for loop works, it works fine - each ford inside is separated
var second = first.replace (pattern, '<b>'+i_vars+'</b>');
.....
unimportant code...
---------------------------------------------------------
The problem I can't figure out is - How to insert a variable (i_vars
) inside the pattern variable inside the reg_exp. I can't get JavaScript to pull the variable from the array above.
Thanks Ahead !
Posted: Sat Oct 02, 2004 9:59 am
by feyd
javascript doesn't do variables inside strings like php does.
Code: Select all
Function abc (first)
{
var i_vars = new Array ("<? echo $var1 ?>", "<? echo $var1 ?>", "<? echo $var1 ?>");
var pattern, second;
for ( var i = 0; i < i_vars.length; i++)
{
pattern = "/" + i_varsїi] + "/gi";
alert(i_varsїi]);
second = first.replace(pattern, '<b>' + ivarsїi] + '</b>');
......
that's untested, as I think you need to use a RegExp object in order to have a variable regularexpression in Javascript. However, you could engineer the regular expression string to not need it in the first place.
...
Posted: Sun Oct 03, 2004 1:17 am
by Calimero
Nope,
with this code no errors are reported, but nothing is highlighted.
RegExp object, ha ?!?
Do I search the docs, under these Keywords.
And if you have some sample code - just to see in example how it works.
Thanks.
Posted: Sun Oct 03, 2004 1:41 am
by feyd
rough example
Code: Select all
<?php $vars = array('word1','wordfoo','word3');
array_walk($vars, 'preg_quote', '/');
?>
function foo(contents)
{
return first.replace(/(<?php echo implode('|',$vars); ?>)/gi,"<b>\$1</b>");
}
...
Posted: Mon Oct 04, 2004 4:18 am
by Calimero
Got the little basta...
Code: Select all
Function abc ()
{
i_vars = new Array ("<? echo $var1 ?>", "<? echo $var1 ?>", "<? echo $var1 ?>");
for ( var i = 0; i < i_vars.length; i++)
{
if (i_varsїi] != "")
{
var pattern = new RegExp (i_varsїi], "gi");
var present = document.getElementById('search_zone').innerHTML;
if
(document.getElementById && document.getElementById('search_zone') && document.getElementById('zone').innerHTML)
{
var desired = present.replace (pattern, '<b>'+i_varsїi]+'</b>');
document.getElementById('search_zone').innerHTML = desired;
}
}
}
}
// The End (This time Happy :) )
NOTES:
Because of a bug it has with form elements, use <p id='search_zone'> </p> tags to limit the area you want to search for the pattern
Oh yeah, pray that your visitors do not enter single to 3 letters that match <html> tags inside your source - or it gets.... interesting !
Thanks for the tip Feyd.
2 out of 15 tasks for my Website v2 finished.
See ya

.