0

Using the following text as my msg variable:

/private UserName:some message without leading whitespace
/private UserName: some message with leading whitespace

And the following javascript to parse it:

if(msg.indexOf('/private') == 0){
    msg = msg.substring(8,msg.length);
    var parts = msg.match(/\s+(.+?)\:\s*(.+?)/);

    alert("Name: " + parts[0]);
    alert("Message: " + parts[1]);
}

I would expect index 0 to contain UserName and index 1 to contain some message with ...

Anyone see what I'm missing?

3 Answers 3

3

Tweak your regex a little bit:

/^\/private\s+(.*?):\s*(.*?)$/

And simplify your code:

var regex = /^\/private\s+(.*?):\s*(.*?)$/;
var parts = regex.exec(msg);

if (parts){
    alert("Name: " + parts[1]);
    alert("Message: " + parts[2]);
}

parts[0] is the entire matched string. You want parts[1] and parts[2].

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

1 Comment

that was it...I'm so used to working with PERL and PHP I forgot about that. Thanks!
1
var msg = '/private UserName:some message without leading whitespace \
/private UserName: some message with leading whitespace';

if (msg.indexOf('/private') == 0) {
   msg = msg.substring(8,msg.length);
   var parts = msg.match(/\s+(.+?)\:\s*(.+?)/);

   console.log("Name: " + parts[0]);
   console.log("Message: " + parts[1]);
}

Prints out

  Name:  UserName:s
  Message: UserName

I would debug the value of your msg and parts variables. Also, check your regex on a site like http://regexpal.com/. It looks like your regex may be matching too much. Do you want it to end with the colon? If so, try something more like this

\s+(\S+?)\:

Comments

0

What you want to do is to split and trim :)

something like :

parts = msg.split(" ",1)[1].split(":",1);

alert("Name: " + parts[0]);
alert("Message: " + $trim(parts[1]));

trim is a jquery function but you could do it with regex :)

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.