Reputation: 42267
I'm attempting to get any words starting with @, such as in "@word", but only get the "word" value.
My sample text is:
@bob asodija qwwiq qwe @john @cat asdasd@qeqwe
My current regex is:
/\B@(\w+)/gi
This works perfectly, except that "@" is still being captured. The output of this match is:
"@bob"
"@john"
"@cat"
I've tried setting the @ in a back reference, but its still including the @ in the results.
/\B(?:@)(\w+)/gi
Upvotes: 1
Views: 137
Reputation: 42140
Here's a neat trick using the String.replace method, which can take a function as the replacement.
var matches = [];
var str = "@bob asodija qwwiq qwe @john @cat asdasd@qeqwe";
str.replace( /\B@(\w+)/g, function( all, firstCaptureGroup ) {
matches.push( firstCaptureGroup );
});
console.log( matches ); //["bob", "john", "cat"]
Upvotes: 2
Reputation: 43
Here is a better solution without additional calculations except of regular expression:
(?<=\B@)(\w+)
Upvotes: -2
Reputation: 141839
You want to use the match array returned from exec
var teststr = '@bob asodija qwwiq qwe @john @cat asdasd@qeqwe';
var exp = /\B@(\w+)/gi;
var match = exp.exec(teststr);
while(match != null){
alert(match[1]); // match 1 = 1st group captured
match = exp.exec(teststr);
}
Upvotes: 5