3

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,

2 Answers 2

6

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);

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

3 Comments

Hmm it don't work, it still only picks out @s from @sam calling that exact function (with the added g flag) like: detect_extractStatusUsers("@sam");
I updated my answer addressing other issues in your functionality.
Woo cheers, I knew it was something simple. Full points given :D
1

You need to call exec repeatedly, until it returns null. Each time it will return a match object, containing all the captures for that match.

I've taken the liberty of rewriting your function the way I would have written it:

function detect_extractStatusUsers(status){
    var rx = /(@[\S]+)/gi,
        match,
        tags = [];
    while (match = e.exec(status)) {
        tags.push(match[1]);
    }
    if (tags.length > 0) {
        alert(tags.join('\n'));
    }
}

Comments

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.