...

View Full Version : Substitution with Regular Expressions



pcon2009
06-14-2007, 06:50 PM
While I do know some javascript, I am having trouble with Regular Expressions. What I want to do is take the value of a certain textbox in a form, check it for some certain characters (namely parenthesis () and brackets []) and then substitute those characters (or remove them) before the form can be submitted. From reading, it seems like this should be possible but I have been experimenting for a few days now with it and can't get it to work at all. This is probably something a little more difficult than I should be trying never having worked with regular expressions before. All help is appreciated! Thanks!

Philip M
06-14-2007, 07:14 PM
This replaces the brackets by X.

<SCRIPT type = "text/JavaScript">

var x = "()[]"
x = x.replace(/[\(\)\[\]]/g, "X");
alert (x);
</SCRIPT>

If you want to simply delete the brackets, then
<SCRIPT type = "text/JavaScript">

var x = "()[]"
x = x.replace(/[\(\)\[\]]/g, "");
alert (x);
</SCRIPT>

If you want to replace each bracket by a different character then:

<SCRIPT type = "text/JavaScript">

var x = "()[]"
x = x.replace(/\(/g, "W");
x = x.replace(/\)/g, "X");
x = x.replace(/\[/g, "Y");
x = x.replace(/\]/g, "Z");

alert (x);
</SCRIPT>

You can test your regular expressions at: http://www.ogauge.co.uk/regextester.html

pcon2009
06-14-2007, 07:42 PM
Okay, I think I understand that much so far. BUT - now I don't know how to actually implement it into a form. What I was trying was something like this:



<body>
<SCRIPT type = "text/JavaScript">
function checkForm()
{
var parcheck = "()[]"
parcheck = parcheck.replace(/[\(\)\[\]]/g, "");
document.getElementById('item1').value = parcheck;
return true;
}
</SCRIPT>

<form name="exampleform" onSubmit="checkForm();">
Item 1:<input type="text" name="item1" id="item1"><br>
<input type="submit" value="Submit">
</form>
</body>


I could be way off base there, but it might help to establish what exactly I am trying to do.

glenngv
06-14-2007, 07:46 PM
<html>
<head>
<script type="text/javascript">
function checkForm(frm)
{
var parcheck = frm.item1.value;
parcheck = parcheck.replace(/[\(\)\[\]]/g, "");
frm.item1.value = parcheck;
return true
}
</script>
</head>
<body>
<form name="exampleform" onsubmit="return checkForm(this);">
Item 1:<input type="text" name="item1" id="item1"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

pcon2009
06-14-2007, 07:50 PM
Thanks so much for the help everyone! I think I should be good now...just have to get it implemented on the actual form, not an example, so I may post again!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum