Search code examples
javascriptregexchatroom

/PM regex syntax for sending message in chat-room


I am working on a AJAX/PHP chatroom and am currently stuck on the regex to detect if a user has send a PM & then work out who it is too and what the message is.

If the user types something like

/pm PezCuckow Hi There you so awesome!

I would like to first test if my string matched that pattern then get 'PezCuckow' and 'Hi There you so awesome!' as strings to post to the PHP.

I have done some research on regex but really have no idea where to start with this one! Can you help?

==Thanks to everyones help this is now solved!==

var reg = /^\/pm\s+(\w+)\s+(.*)$/i;
var to = "";

if(message.match(reg)) {
    m = message.match(reg);
    to = m[1];
    message = m[2];
}

Solution

  • Hows about this:

    var reg = /^\/pm\s+(\w+)\s+(.*)$/i,
        m = '/pm PezCuckow Hi There you so awesome!'.match(reg);
    
    m[0]; // "PezCuckow"
    m[1]; // "Hi There you so awesome!"
    

    That matches "/pm" followed by whitespace " " (liberally accepting extra spaces), followed by the username \w+, followed by whitespace " " agin, then finally the message .* (which is basically everything to the end of the line).