Using multiple "or" || in an if statement

I want to eliminate all . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - from a string. I use

let str = "he.llo*";
let arr = str.split("");
for(let i=0; i<arr.length; i++){
  if(arr[i]=="*"||arr[i]=="+"||arr[i]=="."||arr[i]=="\\") //spelling out every single case here
    arr.splice(i,1)
  }
str = arr.join("")

chaining arr[i]=="+"||arr[i]=="."||arr[i]=="\\" etc… isn’t really clean or “dry”, is there a way I can accomplish this quicker?

Place all chars/string you like to check (those "*", "+", ".", etc…) in an array.

Now in your loop, go for another loop, and check the current index(arr[i]) with each index of those string elems.

var especials=["*", ".", "\\" /*and more...*/];
//...
for(let i=0; i<arr.length; i++){
    for(var a=0;a<especials.length;a++){
        if(arr[i]==especials[a]){
            //your logic
        }
    }
}

Another way is using regex I don’t recommend.

1 Like

If you have lots of things, you can put them in an array and check out the array includes a value:

if(["*", "+", ".", "\\").includes(arr[i]))
2 Likes

never though of using .includes() that way, I tried to use it the other way around arr.includes(*)but I dont think I can pass in multiple arguments into the .includes part

You again :smiley: you answer every question I have… I played arround with the double for loop but I found it relatively complicated for such a small task so I wanted to check if there are any build in methods first but it seems there isn’t so I’ll try out both your and @DanCouper 's answer, thanks

Some solutions are so much JS, just like the one @DanCouper provided(I really didn’t know myself, thanks for sharing dear Dan, you also forgot closing ] for the array). Neat, simple and awesome. But remember not all langs come with such a way, so this might be just JS.

My approaches may be more complex and not small, but compatible. Later when you want start any other language come with C like array(like JS, C++, java, C#,…) that double for loop will work.

In other word, I think more C than JS, so my solutions are. Go with any solution works and you like :smiley:

Keep going on great work, Happy programming.

1 Like

I didn’t know about the includes() method on arrays. That’s awesome and useful!

Edit: Just saw there is a similar method on strings, too :slight_smile:

You can also remove the loop if you’re going down that road:

function removeBadChars(str) {
  const notBadChar = (char) => {
    return ["*", "+", ".", "\\"].includes(char) === false;
  };

  return [...str].filter(notBadChar).join('');
}
1 Like