0

Is there a simple way to check if a string in JavaScript matches a certain thing for example:

Lets say the you wanted to check for the first word which had:

/admin this is a message

Then using JS to look for /admin so that I can direct the message in my chat window??

Sir
  • 8,135
  • 17
  • 83
  • 146
  • possible duplicate of [Javascript StartsWith](http://stackoverflow.com/questions/646628/javascript-startswith) – Nope Jan 30 '13 at 00:07

4 Answers4

2

One way would be to use indexOf() to see if /admin is at pos 0.

var msg = "/admin this is a message";
var n = msg.indexOf("/admin");

If n = 0, then you know /admin was at the start of the message.

If the string does not exist in the message, n would equal -1.

AreYouSure
  • 732
  • 3
  • 9
  • 18
1

Or,

string.match(/^\/admin/)

According to http://jsperf.com/matching-initial-substring, this is up to two times faster than either indexOf or slice in the case that there is no match, but slower when there is a match. So if you expect to mainly have non-matches, this is faster, it would appear.

0

You could use Array.slice(beg, end):

var message = '/admin this is a message';
if (message.slice(0, 6) === '/admin') {
  var adminMessage = message.slice(6).trim();
  // Now do something with the "adminMessage".
}
maerics
  • 151,642
  • 46
  • 269
  • 291
  • hmm the only problem is when the message is added to chat it still keeps /admin in the sentence :( – Sir Jan 30 '13 at 00:10
0

To achieve this, you could look for a "special command character" / and if found, get the text until next whitespace/end of line, check this against your list of commands and if there is a match, do some special action

var msg = "/admin this is a message", command, i;
if (msg.charAt(0) === '/') { // special
    i = msg.indexOf(' ', 1);
    i===-1 ? i = msg.length : i; // end of line if no space
    command = msg.slice(1, i); // command (this case "admin")
    if (command === 'admin') {
        msg = msg.slice(i+1); // rest of message
        // .. etc
    } /* else if (command === foo) {
    } */ else {
        // warn about unknown command
    }
} else {
    // treat as normal message
}
Paul S.
  • 64,864
  • 9
  • 122
  • 138