Check strings for "!"

Don’t worry, you’re not alone.

I don’t think substring() takes negative arguments.

I should have asked this earlier, but do you have a link to the challenge?

No I don’t. Only invitational.

Why you just don’t use for loop? Just count whenever you find “!” , then when you counter hit 3+ “!” return true. If loop iterates through whole string and don’t find more then 3 “!”, then return false.

Ok,

I’m not sure what the instructions to this problem say, but if they are forcing you to use indexOf, fine. If not, You might want to use other, more efficient functions for this task.

I posted all the instructions up top.

The more you play around with JavaScript’s string methods and understand how they work on strings of various kinds, the easier these kinds of problems should become. This page lists some of the most commonly-used ones: https://www.sitepoint.com/15-javascript-string-functions/

Using split() is probably one of the best ways to counter all possible edge cases, btw. Try out this code for yourself and it should give you some ideas…

var str = "hell!oworld!!!!!";
console.log(str.split('!'));

Because what if you have:
I am some ! INTENSE sentence!!

Then do loop backwards … PS: And implement some variable that remembers index of counted “!”. Count only three or more and if their indexes are consecutive, notice before said variable(good to use array for that) return true. If all conditions aren’t met return false.

I don’t think I’ll be doing a loop for this problem. If else seems much more suitable even though I can’t solve it.

Just fleshing out your answer. But yes, you alternative approach will work as well, though it may be simpler than that.

Whichever path you take, it might be better to write your instructions out on paper in pseudocode, if it helps you think out a solution.

I really should get a whiteboard huh?

Or paper. Whichever is more convenient. Great plans start on paper for many things after all.

I don’t understand how I can only use split and not check the string with indexOf?

Because split() returns an array and it’s no longer a string (well technically it’s an array of strings), so you can’t use indexOf().

1 Like

Think about what split does. If I split a sentence at the exclamation marks., then what kind of output should I expect if the sentence is intense.

You just get empty strings.

Arrays can also use indexOf, but there’s no need I feel to use it if you do it this way.

You’re almost correct. You’ll get an array of empty strings except for one.

Well…yeah, strings in an array. But I just don’t know how to word it in code to take this split string (now an array), and check for more than 3 “!”, but if it is interrupted with “!”, return false all within two conditionals? Seems ridiculous to me.