Search and Replace problem with if statement

Search and Replace problem with if statement
0

#1

Tell us what’s happening:
my solution will work with all the tests having to do with capital letters but won’t work for my else statement dealing with replacement words without capital letters in the 0 index. Can anyone see why it always executes the if statement?

Your code so far


function myReplace(str, before, after) {
  let answer = str;
  let regex1 = before;
  let regex2 = after;
  //let regex3 = /[A-Z]/;
 // let indexStart = str.indexOf(regex1);
  let capital = before.charAt(0);
  console.log(capital);
  if (capital==='A'||'B'||'C'||'D'||'E'||'F'||'G'||'H'||'I'||'J'||'K'||'L'||'M'||'N'||'O'||'P'||'Q'||'R'||'S'||'T'||'U'||'V'||'W'||'X'||'Y'||'Z'){
    let cap = regex2[0].toUpperCase();
    let nonCap = regex2.slice(1);
    return answer.replace(regex1, cap + nonCap);
  } else
  return answer.replace(regex1, after);
}

myReplace("A quick brown fox Jumped over the lazy dog", "Jumped", "leaped");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace


#2

yup, this statement will always be equal to TRUE so will always be executed.

You are essentially saying:
If capital is ‘A’ return true OR
if ‘B’ OR
if ‘C’ OR
if ‘D’ …
etc.

All these other ifs are called ‘truthy’ values which always evaluate to true.


#3

so ‘a’===‘A’ because they’re truthy? How do I circumvent that to see if the 0 index of before is equal to a capital letter?


#4

actually no
‘a’ is not equal to ‘A’

what I said was that your if statement was saying
if ‘B’
if ‘C’

there is no comparison happening

If ‘B’ is always true
if ‘C’ is always true
etc.


#5

if you want a quick way to compare you can use a regex statement. There are many ways to do comparisons. (it’s just that your if statement is not phrased correctly and doesn’t do comparisons)


#6

What has been said is basically that you can’t chain OR operator like you did.

The correct way is

if (capital === 'A' || capital === 'B' || ....)

Your expression resolves in this order

(capital === 'A' ) || 'B' => true, because 'B' evaluates to true.

From then on, the expression turns to
true || true || true || true ...

So, that is what is meant by your if statement is always true, regardless to what capital is.

There are much better ways to solve this, so I guess you should look for one.


#7

I get what you say, that makes sense.


#8

I understand now. thanks for your help