How to detect if a input includes more then one word?

Twine Version: 2.3.9(newest)

I currently trying to create a passage with Harlowe where the player can input a name via a prompt, but I want their name to only be one word(no last names). How would I be able to detect if they gave a name with more then one word?

Hi Zalarians,

I would do it like this, using the JavaScript indexOf, since I don’t know of a Harlowier way to do it.

Word indexOf space: (print: "word".indexOf(" "))
Two words indexOf space: (print: "two words".indexOf(" "))

(if: "word".indexOf(" ") is not -1)["Word" has a space] <!-- this will not print -->
(if: "two words".indexOf(" ") is not -1)["Two words" has a space] <!-- but this will -->

Then, instead of “word” and “two words”, just use $name or whatever your variable is.

Hope this helps!

1 Like

Thanks! I’m not too familiar with JavaScript(currently in the process of learning), but after doing some other research on a different problem, I found that I could write a line of code that will detect if the input includes a certain character or in this case, a space. So I used this with Harlow and wrote the following code:

(live: 500ms)[ <!--This allows the below code to run every half a second-->
      (if: $name contains " ")[(set: $name to (upperfirst: (prompt: "Invalid name. Please choose a name with 1 word(no spaces)","")))] 
]

This makes it so if they include a space in their input they would be re-prompted to input a valid name; and because I have the (live:) macro, it will run every half a second(or shorter if I wish). I have other code that will make sure they can use “Mr.” or “Mrs.” before a space(like “Mr. Unknown”) if they wish as well as code to make sure they can’t use any weird characters in their name like “?” or “>”.

Even though I ended up figuring out the problem on my own, I really do appreciate the reply.

Thank you

1 Like