Reputation: 11746
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?
Upvotes: 0
Views: 132
Reputation: 850
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 :)
Upvotes: 0
Reputation: 587
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+?)\:
Upvotes: 1
Reputation: 298146
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]
.
Upvotes: 3