Dylan
Dylan

Reputation: 1

Auto lower case for JavaScript bot

I am trying to make a bot that will convert all the uppercase into lowercase. I want to verify if I am doing it right and in an efficient way.

var temp = /^[a-z][^a-z]*$/;
fb.onMessage(function (msg) {
    var parts = msg['m'].split(" ");
    var cleaned = [];
    for (var i = 0; i < parts.length; i++) {
        var word = parts[i];
        if (temp.test(word)) {
            cleaned.push(word);
        } else {
            cleaned.push(word.toLowerCase());
        }
    }
    msg['m'] = cleaned.join(' ');

    return msg;
});

Upvotes: 0

Views: 67

Answers (2)

samanime
samanime

Reputation: 26615

Are the messages extremely lengthy?

It would probably be just as efficient, if not more so, to simply lowercase all of the words without first checking a pattern. Also, there is no reason to lowercase the words after the fact.

If I'm reading what you wrote up there, you are splitting, checking if it is already lowercase, if not, making it lowercase, then adding all the words back together. It'd be far simpler and faster to just do it all in one go.

fb.onMessage(function (msg) {
    msg.m = msg.m.toLowerCase().replace(/\s+/g, '');
    return msg;
});

I threw in a replace(/\s+/g, '') which would collapse any multiple space sections to a single space. Not sure if this is part of what you were trying to attempt above or not. If you don't care about that, remove the replace for an event more efficient command.

Upvotes: 0

TimWolla
TimWolla

Reputation: 32711

There is no need to split the string up, simply use .toLowerCase() on the complete string. toLowerCase does not care about parts being lowercase already, or parts not being alpha characters.

Upvotes: 1

Related Questions