I want to write a message in a textarea and be able to refer to a person using the @ symbol.
eg
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?
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]);
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.