Convert to small letters and remove space js - javascript

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!")
}
)}

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)

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

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()

Related

Finding something in between characters

How can I get the word in between quotation marks and then replace it with something else from reading from a file
Note: I know how to read and write from files, I just need to know about getting the word from inside quotation marks
If you know the word you're looking for:
let text = 'Sentence with "word" in it';
let wordFromFile = "nothing";
let newText = text.replace('"word"', wordFromFile);
Or else regular expression is useful.
Using Regex(regular expression) with regex replace :
let str = 'How can I get the word in between "quotation marks"';
let word = str.replace(/.*"(.*?)".*/g,'$1');
let replacedWord = 'single quotes';
console.log(str.replace(word,replacedWord))
You can find the word with a quotation mark for example word by /"[^"]+"/ and replace it with other words for example key
const str = 'This is the "word" which inside two quotation marks'
const result = str.replace(/"[^"]+"/g, 'key')
console.log(result)

How to identify a pattern in a string in nodejs

I have the following problem that I have not been able to solve for several hours:
What I want to do is that when I receive a string, identify a pattern in said string and be able to use it later, for example when receiving the text:
"Hello this is an example message, the hashtag of the day is #Phone, you can use it wherever you want"
what I want to do is identify that #Phone and extract it from all that text and for example then be able to make a console.log() of that word that is with the #. So that the result of the console.log is only Phone, for example, or the data that has the #
I have the following code:
const prefix = "#";
client.on("message", function(message) {
if (!message.content.includes(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toUpperCase();
console.log(command)
});
This what returns me is the first element of the text without its first letter, in the case that the text is "Hello, how are you !try this", what it shows is only "ello", and I need it to only show " try"
Use a regular expression to match # (or !) followed by letters or non-space characters or whatever sort of text you want to permit afterwards:
const prefix = '!';
const pattern = new RegExp(prefix + '([a-z]+)', 'i');
const getMatch = str => str.match(pattern)?.[1];
console.log(getMatch('Hello, how are you !try this'));
If the prefix may be a special character in a regular expression, escape it first:
function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
const pattern = new RegExp(escapeRegex(prefix) + '([a-z]+)', 'i');

is there a way for the content.replace to sort of split them into more words than these?

const filter = ["bad1", "bad2"];
client.on("message", message => {
var content = message.content;
var stringToCheck = content.replace(/\s+/g, '').toLowerCase();
for (var i = 0; i < filter.length; i++) {
if (content.includes(filter[i])){
message.delete();
break
}
}
});
So my code above is a discord bot that deletes the words when someone writes ''bad1'' ''bad2''
(some more filtered bad words that i'm gonna add) and luckily no errors whatsoever.
But right now the bot only deletes these words when written in small letters without spaces in-between or special characters.
I think i have found a solution but i can't seem to put it into my code, i mean i tried different ways but it either deleted lowercase words or didn't react at all and instead i got errors like ''cannot read property of undefined'' etc.
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
bot.on('message', message => {
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
This is what i am looking at. the var words line. specifically (/\w+|\s+|[^\s\w]+/g);.
Anyway to implement that into my const filter code (top/above) or a different approach?
Thanks in advance.
Well, I'm not sure what you're trying to do with .match(/\w+|\s+|[^\s\w]+/g). That's some unnecessary regex just to get an array of words and spaces. And it won't even work if someone were to split their bad word into something like "t h i s".
If you want your filter to be case insensitive and account for spaces/special characters, a better solution would probably require more than one regex, and separate checks for the split letters and the normal bad word check. And you need to make sure your split letters check is accurate, otherwise something like "wash it" might be considered a bad word despite the space between the words.
A Solution
So here's a possible solution. Note that it is just a solution, and is far from the only solution. I'm just going to use hard-coded string examples instead of message.content, to allow this to be in a working snippet:
//Our array of bad words
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
//A function that tests if a given string contains a bad word
function testProfanity(string) {
//Removes all non-letter, non-digit, and non-space chars
var normalString = string.replace(/[^a-zA-Z0-9 ]/g, "");
//Replaces all non-letter, non-digit chars with spaces
var spacerString = string.replace(/[^a-zA-Z0-9]/g, " ");
//Checks if a condition is true for at least one element in badWords
return badWords.some(swear => {
//Removes any non-letter, non-digit chars from the bad word (for normal)
var filtered = swear.replace(/\W/g, "");
//Splits the bad word into a 's p a c e d' word (for spaced)
var spaced = filtered.split("").join(" ");
//Two different regexes for normal and spaced bad word checks
var checks = {
spaced: new RegExp(`\\b${spaced}\\b`, "gi"),
normal: new RegExp(`\\b${filtered}\\b`, "gi")
};
//If the normal or spaced checks are true in the string, return true
//so that '.some()' will return true for satisfying the condition
return spacerString.match(checks.spaced) || normalString.match(checks.normal);
});
}
var result;
//Includes one banned word; expected result: true
var test1 = "I am a bannedWord1";
result = testProfanity(test1);
console.log(result);
//Includes one banned word; expected result: true
var test2 = "I am a b a N_N e d w o r d 2";
result = testProfanity(test2);
console.log(result);
//Includes one banned word; expected result: true
var test3 = "A bann_eD%word4, I am";
result = testProfanity(test3);
console.log(result);
//Includes no banned words; expected result: false
var test4 = "No banned words here";
result = testProfanity(test4);
console.log(result);
//This is a tricky one. 'bannedWord2' is technically present in this string,
//but is 'bannedWord22' really the same? This prevents something like
//"wash it" from being labeled a bad word; expected result: false
var test5 = "Banned word 22 isn't technically on the list of bad words...";
result = testProfanity(test5);
console.log(result);
I've commented each line thoroughly, such that you understand what I am doing in each line. And here it is again, without the comments or testing parts:
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
function testProfanity(string) {
var normalString = string.replace(/[^a-zA-Z0-9 ]/g, "");
var spacerString = string.replace(/[^a-zA-Z0-9]/g, " ");
return badWords.some(swear => {
var filtered = swear.replace(/\W/g, "");
var spaced = filtered.split("").join(" ");
var checks = {
spaced: new RegExp(`\\b${spaced}\\b`, "gi"),
normal: new RegExp(`\\b${filtered}\\b`, "gi")
};
return spacerString.match(checks.spaced) || normalString.match(checks.normal);
});
}
Explanation
As you can see, this filter is able to deal with all sorts of punctuation, capitalization, and even single spaces/symbols in between the letters of a bad word. However, note that in order to avoid the "wash it" scenario I described (potentially resulting in the unintentional deletion of a clean message), I made it so that something like "bannedWord22" would not be treated the same as "bannedWord2". If you want it to do the opposite (therefore treating "bannedWord22" the same as "bannedWord2"), you must remove both of the \\b phrases in the normal check's regex.
I will also explain the regex, such that you fully understand what is going on here:
[^a-zA-Z0-9 ] means "select any character not in the ranges of a-z, A-Z, 0-9, or space" (meaning all characters not in those specified ranges will be replaced with an empty string, essentially removing them from the string).
\W means "select any character that is not a word character", where "word character" refers to the characters in ranges a-z, A-Z, 0-9, and underscore.
\b means "word boundary", essentially indicating when a word starts or stops. This includes spaces, the beginning of a line, and the end of a line. \b is escaped with an additional \ (to become \\b) in order to prevent javascript from confusing the regex token with strings' escape sequences.
The flags g and i used in both of the regex checks indicate "global" and "case-insensitive", respectively.
Of course, to get this working with your discord bot, all you have to do in your message handler is something like this (and be sure to replace badWords with your filter variable in testProfanity()):
if (testProfanity(message.content)) return message.delete();
If you want to learn more about regex, or if you want to mess around with it and/or test it out, this is a great resource for doing so.

Javascript: split a string according to two criteria?

I am trying to count the number of sentences in a paragraph. In the paragraph, all sentences end with either ''.'' or ''!''.
My idea is to first split the paragraph into strings whenever there's a ''.'' or ''!'' and then count the number of splitted strings.
I have tried
.split('.' || '!')
but that does not work. It only splits strings whenever there is a ''.''
May I know how to deal with this?
Just use a Regexp, it's pretty simple ;)
const example = 'Hello! You should probably use a regexp. Nice isn\'t it?';
console.log(example.split(/[.!]/));
You will need to use a regex for this.
The following should work:
.split(/\.|!/)
You can use regex /\.|!/ in split() as str.split(/\.|!/) :
var str = 'some.string';
console.log(str.split(/\.|!/));
str = 'some.string!name';
console.log(str.split(/\.|!/));
const sampleString = 'I am handsome. Are you sure?! Just kidding. Thank you.';
const result = sampleString.split(/\.|!/)
console.log(result);
// to remove elements that has no value you can do
const noEmptyElements = result.filter(str => str);
console.log(noEmptyElements);
Try below code it will give you an exact count of sentences in the paragraph.
function count(string,char) {
var re = new RegExp(char,"gi");
return string.match(re).length;
}
function myFunction() {
var str = 'but that! does! not work. It only splits strings whenever there is a. ';
console.log(count(str,'[.?!]'));
}

Remove ALL white spaces from text

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}

Categories