views:

59

answers:

2

Hi,

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?

+5  A: 

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]);
}
Darin Dimitrov
+1  A: 

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.

epascarello