0

I want to write a message in a textarea and be able to refer to a person using the @ symbol.

e.g

Please call @Larry David regarding something

When submitting the form, I want to extract the persons name ie Larry David.

How do I go about extracting this string with Jquery?

4
  • 3
    What if the person name is Larry David Regarding? I think the best you can do here is to extract Larry. Commented Oct 9, 2010 at 23:14
  • what do you think of using the same mechanism as SO uses for tags (i.e. smart autocompletion)? it's not an easy thing to do right though Commented Oct 9, 2010 at 23:17
  • 1
    why with jQuery?? using a regex would be more efficient like the example in the answer below.. Commented Oct 9, 2010 at 23:32
  • What are valid names? Does the name always matches a username on database or something? Commented Oct 9, 2010 at 23:50

2 Answers 2

5

What if the person name is Larry David Regarding? I think the best you can do here is to extract Larry:

var result = $('#textareaId').val().match(/\@(\w+)/);
if (result != null && result.length > 1) {
    alert(result[1]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Well to match what you asked for it would be:

var str = "Please call @Larry David regarding something";
var re = /@(\w+\s\w+)/;

var name = str.match(re);
if(name){
    alert(name[1])
}

But it would fail for names like foo-bar, O'Donald, etc.

A regular expression such as

var re = /@(\w+\s[\w-']+)/;

would be a little better, but still will fail with other names.

Without a better way of figuring out where the name ends, you may have errors with names.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.