1

To simplify my question using the statement below, how can I have my javascript always print to console what the user typed?

A blip from my code

if (userTyped === 'getname '+ variable) {

Where 'variable' will always equal whatever last half of the string they typed. For example, if a user types "getname 398502" then log it to the console, or if a user types "getname 598024" then log that to the console.

So as long as they typed 'getname ' then print all of what they typed.

2
  • 4
    if (userTyped === 'getname ' + variable) { ? Commented Feb 4, 2013 at 17:24
  • 1
    Perhaps validate the command with a regular expression, and use capture groups for the command arguments. Commented Feb 4, 2013 at 17:25

4 Answers 4

1

You will want to make sure 'getname ' is at the start of your string:

if (userTyped.indexOf('getname ') === 0) {
    console.log(userTyped);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I probably explained myself poorly, but this has proven the solution for me! Danke everyone!
1

You could use a regular expression to validate the command and extract the argument. Something like:

var input = 'getname 19395029'; //Sample input
var re = /^getname (\d+)$/g;
var match = re.exec(input);
if(match) // Input matches command format
    window.alert('Getting name: ' + match[1]);

Comments

1

Try

if( /^getname /i.test( input ) ) { 
    console.log( input.replace( /^getname /i, "" ) ); 
}

Fiddle here

Comments

0

can equal anything the user typed

Then you don't want to test against a variable (with a certain value). Instead, you want to test the first part against 'getname' and parse the second part into a variable. You can do that using regular expressions, for example:

var match = userTyped.match(/^getname (\d+)$/);
if (match) {
    var variable = match[1]; // maybe parseInt(match[1], 10) ?
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.