Javascript pairing

I want to get the characters after the @ character before the space character.

eg. if my line is like hello @world. some gibberish.@stackoverflow hello @world. some gibberish.@stackoverflow . Then I want to get the symbols "world" and "stackoverflow".

Here is what I tried.

 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 @ occurrences and spaces, and then trim this part to get my content, but I would like to get a better solution / suggestion for this without REGEX. Thanks in advance.

+5
source share
1 answer

You can use this regex:

 /@(\S+)/g 

and capture the captured groups using the exec method in the loop.

This regular expression matches @ , and then \S+ matches 1 or more non-spatial characters that are grouped into 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: Please note that you will need to use

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

if you do not want to write DOT after word .

+4
source

All Articles