I have a regex to get @user from a textarea. When user type something with @ I get it.
My problem is, I want to get just the last match, not all of them.
eg:
user type:
@josh and @marie = want to show @marie
@josh loves @marie and @anne = show @anne
my code is showing like this:
@josh,@marie,@anne
Can I get just the last @something entry? (while user is typing)
var word=/@(\w+)/ig;
$("#comment").on("keyup",function() {
var content = $(this).val();
var name = content.match(word);
var dataString = name;
if(name.length > 0) {
$("#result").text(name);
}
return false();
});
html
<textarea id=comment>@josh and @marie</textarea>
<div id=result></div>
https://jsfiddle.net/dcs5pat8/ (press on textarea)
Besides getting all matches and obtain the last one, you can use capture groups to get the last match:
var word=/.*(@\w+)/i;
var name = content.match(word)[1];
Or using exec, the whole would look like:
var word=/.*(@\w+)/i;
$("#comment").on("input",function() { //changed keyup to input
var content=$(this).val();
var match = word.exec(content);
if(match){
$("#result").text(match[1]);
}
});
Fiddle
PS, if your goal is a more generic approach and you need to switch between getting all words and a single one, I'd recommend keeping the global match and getting the last as in Jonas' answer.
My suggestion is that you show only the last entry of your results.
You can do that by changing the line:
var name = content.match(word);
to
var names = content.match(word);
var name = names[names.length - 1];
On more detail, what this does is it gets all the results from your regex, then it attributes the last item of the array to the name
variable.
Hope this was helpful.
You can simply select or pop the last match in the array of match returned by .match()
var word=/@(\w+)/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var matches = content.match(word);
var lastmatch = matches.pop();
//IF YOU NEED TO KEEP INTACT THE VAR MATCHES
//var lastmatch = matches[matches.length - 1];
if(name.length>0){
$("#result").text(lastmatch);
}
return false();
});
JSFiddle
Use this regex '/@(\w+)$/ig' insted of '/@(\w+)/ig'.
And then your code will run like a charm. ;)
var word=/@(\w+)$/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var name = content.match(word);
var dataString = name;
if(name.length>0){
$("#result").text(name);
}
return false();
});
See it hear https://jsfiddle.net/dcs5pat8/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With