Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Matching Javascript

Tags:

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.

like image 211
Rishik Rohan Avatar asked May 26 '16 13:05

Rishik Rohan


People also ask

How do you check if a string contains another string in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you match strings?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

How do you check if a string is matched?

If you need to know if a string matches a regular expression RegExp , use RegExp. prototype. test() . If you only want the first match found, you might want to use RegExp.


1 Answers

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.

like image 57
anubhava Avatar answered Oct 04 '22 20:10

anubhava