0

I'm having trouble trying to check a string for words from an array and if it includes the word replace them.

var blocked = [
  "inappropriate word one",
  "inappropriate word two",
];

var message = "the message has an inappropriate word one";

if (blocked.some(string => message.includes(string))) {
  message = message.replace(string, "blocked")
}

2
  • "string" is only available in the "some" method. you will need to iterate the array of blocked words. Commented Oct 27, 2021 at 15:59
  • string is not accessible where you are using it, but why not loop over blocked array and call replace for each, replace will not work if the sentence doesn't exist, no need to pre-check Commented Oct 27, 2021 at 15:59

2 Answers 2

3

In the body of the if the variable string is not available anymore because it's only valid in the callback of some. So just loop over the blocked words and do the replacement.

blocked.forEach(string => {
  if (message.includes(string)) message = message.replace(string, "blocked");
})

In principle the check isn't necessary. If the search value is not contained in the string, nothing will be replaced, so you can just do the following:

blocked.forEach(string => {
  message = message.replace(string, "blocked");
})

But be aware that String::replace(search, replacement) only replaces the first occurence of search if it is a string. So if your "badword" occurs more than once, only the first occurence will be replaced. So it might be better to define your blocked words as regex, because this way you can replace multiple occurrences.

var replacements = [
  /badwordone/gi, 
  /badwordtwo/gi
]

replacements.forEach(r => { 
  message = message.replace(r, "blocked");
})
Sign up to request clarification or add additional context in comments.

Comments

1

You are using message.replace(string), but string isn't defined outside the scope of that some() method. It is only available inside the some() method and is not available outside. Therefore your code doesn't work.

2 Comments

While it's correct, that string isn't availabe outside of the some method, your conclusions are rather strange. Because even if you assign something to a global variable within the callback of some this global variable can only contain a single value. So you will only be able to replace one of the blocked words ...
Oops. This was my first answer so sorry...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.