0

I'm trying to catch a person's name. The name would be entered in a text box such as:

my name is Robert or yes my name is Robert etc.

I don't know where the actual name will fall however because of intro words etc.

I was thinking something like this.

  1. I search for "my name is"
  2. I capture it in an array
  3. I split the array
  4. I now know the actual name follows as such:

namesParts[0] - would be "my"

namesParts[1] - would be "name"

namesParts[2] - would be "is"

namesParts[3] - would be the name i'm looking for.

Something perhaps like the below but this doesn't work.

if (input.search("my name is")!= -1) {
    var names = input.match(/my name is/);
    var namesParts = names.split(' '); 
    var one = namesParts[3];
    document.result.result.value = "Ok your name is "+one+".";
    return true;
}
6
  • will the intro words always be the same? Commented May 12, 2013 at 21:39
  • "Robert is my name." "I'm known as Robert." "Call me Bruce." "Robert Peters." Commented May 12, 2013 at 21:49
  • 1
    @nnnnnn: Call me may be Commented May 12, 2013 at 21:50
  • @zerkms - Call me anything, as long as you call me. Commented May 12, 2013 at 21:51
  • @zerkms Hey! I just met you! Commented May 12, 2013 at 22:24

2 Answers 2

1

If all other words will start with lower case letter you could use

'my name is Robert'.match(/[A-Z]+\w*/);

otherwise

'My name is Robert'.match(/my name is (\S+)/i);
Sign up to request clarification or add additional context in comments.

3 Comments

ok once I got the match then something like this: var names = names[1];
@mister movie: I'm still not sure what you're talking about
I was trying to fit your example into my original "if statement" presented above. I think I figured it out. Thanks!
0

Check the JavaScript String.split Method.

Examples:

var str="my name is Robert";
var n=str.split('my name is ');
alert('1. Length: '+n.length +' Array: '+ n);

var str="my name is Robert";
var n=str.split(' ');
alert('2. Length: '+n.length +' Array: '+ n);

var str="my name is Robert";
var n=str.split('');
alert('3. Length: '+n.length +' Array: '+ n);

Live example: http://jsfiddle.net/a4D8q/

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.