Question


"UserInput" is what the user enters


The user will say Hello _______
For example here: We will use Hello World

    var input = UserInput;
    // Let's say the user inputs hello world
    if(input == "hello") {
      var cut = input.substr(6)
      console.log(cut)
    }

The user is inputting "hello world" but the if statement will not pick that up

my goal is to get the users input from an if statement, but have it so I can substr part of what they are saying

Was it helpful?

Solution

Use string.indexOf to see if a string contains another string

var input = UserInput;
// Let's say the user inputs hello world
if ( input.indexOf( "hello" ) != -1 ) {
    var cut = input.substr(6)
    console.log(cut)
}

note that used this way it's case sensitive

OTHER TIPS

You can split up the input as well... fun with strings and arrays

//Lets say you have this string...
var input = "Hello world let me go back to bed"

//Split into an array
var eachWord = input.split(" ") //["Hello", "world", "let".....]

//Get first word
var firstWord = input[0];//"Hello"

//Get rest of sentence
var theRest = input.splice(1, input.length); //["world", "let", "me"...]

//put this into a string
theRest = theRest.join(" ") //"world let me...."

Now you can do whatever you like. Also, it's important to make the string either lowercase or uppercase when you check against it

(firstWord.toLowerCase === "hello")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top