remove a string from within a string

S

soni29

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?

thank you.
 
S

Steve van Dongen

Andrew Urquhart said:
*soni29* said:
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, "ig");


That should likely be
var objRE = new RegExp("\b" + objCensorWords + "\b", "ig");
so that you only match it if word boundaries exist on both sides.

Regards,
Steve
 
R

rh

Andrew Urquhart said:
*soni29* said:
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, "ig");
strData = strData.replace(objRE, "");


As a note, when in possession of a set of alternates in an array, it's
often more efficient to generate the RegExp as, for example:

re = new RegExp("\\b("+objCensorWords.join("|")+")\\b","ig")

thereby eliminating the need for a loop of repeated generation of
RegExps and their application to the string. Such a change will bury
the execution within standard regular expression processing.

../rh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top