0

I've this problem with this code. This code should return "Interior decoration learning" but it keeps returning "home decoration learning", What am I doing wrong?

var forbidden = "home decor learn"; var items = [ ["decor", "decoration"], ["learn", "learning"], ["home", "interior"], ]; for(i = 0; i<items.length; i++){ if(forbidden.indexOf(items[i][0])){ forbidden = forbidden.replace(items[i][0], items[i][1]); } } document.write(forbidden); 

Thank you,

1
  • If nothing is found indexOfis -1, not false. Commented Apr 7, 2018 at 0:05

1 Answer 1

2

forbidden.indexOf(items[i][0]) returns the position of the match or -1 if there is no match. That means it is truthy when there is no match or when there is a match anywhere other that the start of the string. The only time it returns a falsy value is when it matches the very start of the string and returns 0, as is the case with "home" in your scenario.

To use indexOf as a test to see if a string contains a value you need your test to check whether it returned -1 or any other number (EG. you can use conditions like !== -1 or >= 0). In modern JavaScript engines or with a very simple SHIM you can use String.prototype.includes instead which returns a boolean and better signifies your intention.

In your case you don't really need an if statement at all. Just do the replacement and rely on the fact that replace is a no-op if it can't find the replacement pattern:

var forbidden = "home decor learn"; var items = [ ["decor", "decoration"], ["learn", "learning"], ["home", "interior"], ]; for(i = 0; i<items.length; i++){ forbidden = forbidden.replace(items[i][0], items[i][1]); } document.write(forbidden);

Note: String.prototype.replace only replaces the first match when used with string or a non-global regex as the replacement pattern. That means your code will allow forbidden words, so long as the occur at least twice. A workaround for that is beyond the scope of this answer.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.