Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex Help!

I am trying to match a @ tags within this string:

 @sam @gt @channel:sam dfgfdh sam@sam

Now in regex testers this works @[\S]+ (with settings on JS testing) to pick out all strings starting with @ so in them I get:

@sam @gt @channel:sam @sam

But then in browsers using this code:

function detect_extractStatusUsers(status){
var e = new RegExp('@[\S]+', 'i');
m = e.exec(status);
var s= "";

if (m != null) {
    for (i = 0; i < m.length; i++) {
        s = s + m[i] + "\n";
    }
    alert(s);
}

return true;
}

I can only get one single match of @ (if I'm lucky, normally no match).

I must be missing something here and my eyes have just been looking at this for too long to see what it is.

Can anyone see what's wrong in this function?

Thanks,

like image 721
Sammaye Avatar asked Jul 21 '26 12:07

Sammaye


1 Answers

You need to:

  • use the global search g setting
  • escape your \
  • use match instead of exec

    var e = new RegExp('@[\\S]+', 'gi');

    m = status.match(e);

like image 188
mVChr Avatar answered Jul 23 '26 02:07

mVChr