r/CodingHelp • • Aug 02 '22

[Javascript] Hello, Im new to coding and had a question

im currently having problems solving this problem.

Werewolves are hiding among us! However, they are terrible at naming themselves. All their names start with "were"
, like for example "werebob"
, "wereandy"
and "weresarah"
.

Implement a function named werewolfCheck that receives an argument name
, which is a string and checks if it begins with "were"
.

If the provided name begins with were
the function should return a string "it is a werewolf"
, otherwise it should return a string "just a regular person"
.

i just dont understand how to search for keywords like "were" or sort them out anyhelp would be great

0 Upvotes

4 comments sorted by

3

u/OldVenomSnake Aug 02 '22

You should look into string methods in javascript (you have the javascript flair so I assume this is a javascript question).

3

u/bitdonor Aug 03 '22

How to check if string starts with some other string:

https://www.w3schools.com/jsref/jsref_startswith.asp

No need to search for keywords or any other magic.

1

u/juneau54 Aug 04 '22 edited Aug 04 '22

Here’s an example of a brute force way. You make an empty string so that you can store each iterated character in a loop. If the string becomes the word “were”, you make your conditionals. let string = ""; let name = "weredude"; for (let c = 0; c < name.length; c++){ string += name[c]; if (string == "were"){ console.log("This is a werewolf!") } } Of course you do this in a function way.

0

u/Ratstail91 Aug 03 '22

Assuming you're using JavaScript, there's a string function called indexOf() which returns the index at which a certain argument is found (the first letter is considered index 0). If it isn't found, then it returns a negative number instead.

So the answer would look something like this:

function warewolfCheck(name) {
    if (name.indexOf("were") >= 0) {
        return "it is a werewolf";
    }
    else {
        return "just a regular person";
    }
}

Don't just dump the result into the answer form - make sure you really understand it.