Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get only the last match? .match(word)

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)

like image 789
RGS Avatar asked Mar 03 '16 12:03

RGS


4 Answers

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.

like image 173
Me.Name Avatar answered Nov 20 '22 13:11

Me.Name


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.

like image 28
Jonas Meinerz Avatar answered Nov 20 '22 12:11

Jonas Meinerz


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

like image 2
Mr Rubix Avatar answered Nov 20 '22 14:11

Mr Rubix


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/

like image 1
Roger Russel Avatar answered Nov 20 '22 12:11

Roger Russel