*soni29* wrote:
hi,
how can i remove a string from an existing string in javascript. i
have a textbox in a form and want to make sure that when the user
clicks a button that certain words are moved, like all instances of
"hello" should be taken out of the text the user typed in the textbox.
any ideas?
An example of one method:
<script type="text/javascript">
var objCensorWords = new Array("ears", "feet", "navel");
function Censor(objForm, strElementName) {
if (objForm && objForm.elements[strElementName]) {
var objElement = objForm.elements[strElementName];
var strData = objElement.value;
for (var i=0; i<objCensorWords.length; ++i) {
var objRE = new RegExp(objCensorWords[i], "ig");
strData = strData.replace(objRE, "");
}
objElement.value = strData;
return true;
}
else {
alert("An error message");
}
return false;
}
</script>
<form action="page.ext" method="post"
onsubmit="return Censor(this, 'mydata');">
<fieldset>
<legend>Example Form</legend>
<label for="id_mydata">Your data:</label>
<textarea name="mydata" id="id_mydata" cols="20" rows="3">The King has
donkeys' ears</textarea>
<input type="submit" value="Submit">
</fieldset>
</form>
Might be enough to give you an idea of how to implement your own.
Turning off javascript will present a whole new problem. In this example
strings in the 'objCensorWords' array would need to be escaped if they
contain special characters that could be interpretted by the regular
expression engine (unless you specifically wanted that behaviour).
--
Andrew Urquhart
- FAQ:
www.jibbering.com/faq/
- Archive:
www.google.com/groups?q=comp.lang.javascript
- Contact me:
http://andrewu.co.uk/contact/