kai Taylor
kai Taylor

Reputation: 795

Javascript/Jquery - how to replace a word but only when not part of another word?

I am currently doing a regex comparison to remove words (rude words) from a text field when written by the user. At the moment it performs the check when the user hits space and removes the word if matches. However it will remove the word even if it is part of another word. So if you type apple followed by space it will be removed, that's ok. But if you type applepie followed by space it will remove 'apple' and leave pie, that's not ok. I am trying to make it so that in this instance if apple is part of another word it will not be removed.

Is there any way I can perform the comparison on the whole word only or ignore the comparison if it is combined with other characters?

I know that this allows people to write many rude things with no space. But that is the desired effect by the people that give me orders :(

Thanks for any help.

function rude(string) {

var regex = /apple|pear|orange|banana/ig; 
//exaple words because I'm sure you don't need to read profanity 

var updatedString = string.replace( regex, function(s) {
    var blank = "";
    return blank;
});
return updatedString;
}

$(input).keyup(function(event) {
   var text;
   if (event.keyCode == 32) {
       var text = rude($(this).val());
       $(this).val(text);
       $("someText").html(text);
   }
}

Upvotes: 2

Views: 1198

Answers (1)

sabof
sabof

Reputation: 8192

You can use word boundaries (\b), which match 0 characters, but only at the beginning or end of a word. I'm also using grouping (the parentheses), so it's easier to read an write such expressions.

var regex = /\b(apple|pear|orange|banana)\b/ig; 

BTW, in your example you don't need to use a function. This is sufficient:

function rude(string) {
  var regex = /\b(apple|pear|orange|banana)\b/ig; 
  return string.replace(regex, '');
}

Upvotes: 3

Related Questions