Convert to small letters and remove space js

Viewed 1053

I am new to javascript currently working on discord bots
I coded a bot which responds to messages but when I give input in capital letters or by giving space the bot not responding please help me to fix this

This is my code and if I give input like "Hi bro"
It doesn't respond

bot.on("message", async message => {
    if(message.author.bot || message.channel.type == 'dm') return;
  
    let prefix = "-";
    let messageArray = message.content.split(" ");
    let cmd = messageArray[0];
    let args = messageArray.slice(1);
    
    if(cmd === `${prefix}hibro`) {
        return message.reply("Hi bro!")
    }
)}
5 Answers

Mostly your solution is to bring to the same format either making lowercase all the letters or capital. It's up to you, but better lowercase. Also you can use trim() to avoid multiple spaces.

const str = 'Whatever Text You    Want';
const res = str.replace(/\s+/g,'').toLowerCase();
console.log(res)

this shall do the trick.

if you get the message using message.content than replace all of the spaces with dashes using replaceAll and conver it to lower case with .toLowerCase()

message.content.replaceAll(' ', '-').toLowerCase()

Compare after making string lowercase. Example

var str = "Hello World!";
var res = str.toLowerCase();

If you want to convert all the letters to the small case then Javascript has toLowerCase() method available for strings. To replace the whitespace you can use the replace method.

So the following code will give the output: hibro!

"Hi bro!".toLowerCase().replace(/\s/g,'')

/\s/g finds all the occurrences of white space in the strings.

May be you can try the below,

const str1 = 'Whatever Text You    Want';
    var k=[...str1.toLocaleLowerCase()];
    var s='';
    k.forEach(temp=>{
        s+=(temp!=' ')?temp:''
    })

a.trim() only removes the trailing spaces at the end and the beginning of the string, it won't capture in between spaces.

May be you can refer about String.prototype.trim() MDN docs here

Related