Rishik Rohan Rishik Rohan - 4 months ago 7x
Node.js Question

String Matching Javascript

I want to get the characters after @ symbol till a space character.

for eg. if my string is like

hello @world. some gibberish.@stackoverflow
. Then I want to get the characters 'world' and 'stackoverflow'.

Here is what I have been trying.

var comment = 'hello @world. some gibberish.@stackoverflow';
var indices = [];
for (var i = 0; i < comment.length; i++) {
if (comment[i] === "@") {
for (var j = 0; j <= i; j++){

I can get the occurences of @ and spaces and then trim that part to get my content but I'd like a better solution / suggestion for this, with without REGEX. Thanks in advance.


You can use this regex:


and grab captured groups using exec method in a loop.

This regex matches @ and then \S+ matches 1 or more non-space characters that are grouped in a captured group.


var re = /@(\S+)/g; 
var str = 'hello @world. some gibberish.@stackoverflow';
var m;
var matches=[];

while ((m = re.exec(str)) !== null) {

document.writeln("<pre>" + matches + "</pre>");

PS: Note you will need to use


if you don't want to capture DOT after word.