Need a smidge of help with some javascript, if there’re any xperts out there… (sorry if this is the wrong forum… mods/admins feel free to move it…)
I’m working on a VBScript/ASP/Access database web-based system and since MS Access SQL hates apostrophes, I’m having to use a little javascript “onclick” function to filter entries to replace single apostrophes (’) with doubles (’’). It works fine, except… when a user puts more than one apostrophe in the entry string (e.g. “It’s a cow’s head!”) the filter catches only the first instance, and a lovely error page appears. Is there anyone out there who might be able to help me tweak this code to catch multiple instances? (I’m not at all anywhere near an expert in this, so please type slowly! )
Here’s what I’m currently using:
<script type="text/javascript">
function formfilter()
{
for (i=0; i<document.forms[0].elements.length; i++)
{
var tmp=document.forms[0].elements[i].value;
if(tmp.match("'"))
{
var ne=tmp.replace("'","''");
document.forms[0].elements[i].value=ne;
}
}
}
</script>
BTW, please refrain from snide posts about how I should be using PHP/MySQL or some such… I’m well aware that the tech I’m using sux… its just what I’m familiar with ATM. Be kind. & TIA!
Its served to a local network (intranet) only behind company firewall… not a critical data system, and have you ever seen those ads for Monster.com where the guy’s working with a buncha chimps? You get the picture… no worries from coworker meddling 'round here. 'Sides, if someone working here were to get to cracking into IS systems, there’s much higher-stake targets to risk getting fired over than this piddly one.
Got any ASP server-side solutions to point me at, btw?
Thanks for the tip, agent. We’ll see what we can do…
The problem is that the replace function (unless told otherwise) only works on the first match. In his example above he wants to replace one single quote with two single quotes. This has a different challenge than replacing something with something completely different.
Using a loop, on the first pass it will see the first single quote, replace it with two single quotes and stop. Then it will go through the loop again. The first single quote from last time will still be there so it will replace it and go through the loop again. Each time, the first quote will be replaced with two and just get bigger and bigger and bigger, etc. (see: infinite loop)
The real solution is to use the correct method for doing a ‘replace all’ which is to construct your match pattern like I outlined above.
/'/g
g meaning ‘global’