Rishik Rohan Rishik Rohan - 6 months ago 24
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] === "@") {
indices.push(i);
for (var j = 0; j <= i; j++){
startIndex.push(comment[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.

Answer

You can use this regex:

/@(\S+)/g

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.

Code:

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

while ((m = re.exec(str)) !== null) {
  matches.push(m[1]);
}

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

PS: Note you will need to use

/@([^.\s]+)/g

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

Comments