5

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.

3

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Worked perfectly fine. Also any good reference if you can recommend with plenty of examples for learning regex? Thanks in advance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.