How to Test if a String Has an Array Entry [duplicate] - javascript

This question already has answers here:
Javascript- Matching values from array to substring of variable
(3 answers)
Closed 4 years ago.
I'm creating a Discord bot with Discord.js that catches whenever someone swears in a message. I have an array that's full of common swear words, abbreviations, racial and sexual slurs, etc. that I want it to catch.
const SwearWords = ["a##","ba##ard","bi###","c#ck","c#nt","d#ck","f#ck","gay","k#ke","n#gg","omfg","sh#t","wtf"];
(the array doesn't have all the hashtags, I just added them in for the post)
What I tried using originally was if (lcMsg.includes(SwearWords)) {return;} with lcMsg being message.content.toLowerCase(); so that it can catch users swearing no matter how they capitalize it. But that didn't work so I tried using .entries() and .every() after Google-ing an answer (and I never found any).
I imagine .map() would work? I don't know because I haven't learned how to use that. If someone could help me figure this out that'd be great.

The array .some method will be helpful here. Combine that with your .includes to see if any of those words are present in the message:
const SwearWords = ["a##","ba##ard","bi###","c#ck","c#nt","d#ck","f#ck","gay","k#ke","n#gg","omfg","sh#t","wtf"];
const saltyMessage = "wtf, git gud scrub";
const niceMessage = "gg wp";
function hasBadWord(msg) {
return SwearWords.some(word => msg.includes(word));
}
console.log("Message and has swear word?:", saltyMessage, " -> ", hasBadWord(saltyMessage));
console.log("Message and has swear word?:", niceMessage, " -> ", hasBadWord(niceMessage));
Additionally, you can find which word the message had by using .find instead of .some:
const SwearWords = ["a##","ba##ard","bi###","c#ck","c#nt","d#ck","f#ck","gay","k#ke","n#gg","omfg","sh#t","wtf"];
const saltyMessage = "wtf, git gud scrub";
const niceMessage = "gg wp";
function whichBadWord(msg) {
return SwearWords.find(word => msg.includes(word));
}
console.log("Message and has swear word?:", saltyMessage, " -> ", whichBadWord(saltyMessage));
console.log("Message and has swear word?:", niceMessage, " -> ", whichBadWord(niceMessage));

You need to use the function some and function includes
lcMsg.replace(/\s+/g, ' ').split(' ').some((w) => SwearWords.includes(w));
Look how the variable lcMsg is being prepared to loop over its words.

Related

JavaScript RegEx: How do I utilise named capture groups? [duplicate]

This question already has answers here:
Javascript: Named Capture Groups
(2 answers)
Named capturing groups in JavaScript regex?
(10 answers)
Closed last month.
I am currently working at a Plugin for RPG Maker MZ and for that, i learned how to use RegEx for analyzing the Content of a Notetag. While my first try with them was actually pretty good, i assume it didn't used the full potential of RegEx and because i need to expand the my RegEx anyway so the user has more options, i wanted to try out named capture groups for better readability and easier access for me as a developer.
Unfortionatly, i wasnt able to find out how to get the "group" object of the objects i got from the Iterator from matchAll(). So my question would be how to analyse the content of a named capture group in javascript.
Important: as far as i saw, the other questions didnt answer the question why i wasnt be able to find the right group object. also, most of the answers are with the exec function instead of the matchAll function.
The for this part relevant Code is:
const regex1new = /(?<ItemCategory>Item|Armor|Weapon)\s*:\s*(?<ID>\d+)\s*(?<Weight>w:(?<WeightFactor>\d+))?/gm;
let foundTagEntrysList = Array.from(this.enemy().meta.HellsCommonDropList.matchAll(regex1new), entry => entry[0]); //If you wanna reproduce this, just replace this.enemy().meta.HellsCommonDropList with a string
newTagsAnalyser();
function newTagsAnalyser() {
foundTagEntrysList.forEach(matchedElement => {
let Item;
let Weight;
let ID = matchedElement.groups.ID;
switch (matchedElement.groups.ItemCategory) {
case "Item":
Item = $dataItems[ID];
break;
case "Weapon":
Item = $dataWeapon[ID];
break;
case "Armor":
Item = $dataArmor[ID];
break;
default:
break;
}
if (typeof matchedElement.groups.Weight !== 'undefined'){
Weight = matchedElement.groups.WeightFactor;
}
commonItemDataMap.set(Item, Weight);
});
}
What did i expected?
That the matechedElement.group.xxx returnes the content of the group that is named xxx.
What was the result?
rmmz_managers.js:2032 TypeError: Cannot read property 'ID' of undefined

Is it good to use rename object key in function parameters?

Im quite new to Javascript. When im trying to learn the destructuring, i accidentially found out that i can rename the variable and use the old one as linking word to make the function easier to read (for me).
function getWords({ beginWith: character, from: text }) {
return text.split(" ").filter(word => word.startsWith(character));
}
let msg = "Hello world.";
let words = getWords({ beginWith: "H", from: msg });
console.log(words);
However, I wonder if this has any side effects to the program or not and should I continue to use it?

String replace in JavaScript (like Query Binding) [duplicate]

This question already has answers here:
How can I do string interpolation in JavaScript?
(21 answers)
Closed 3 years ago.
Thank you for answering my question, I think this is not interpolation so I change the title and before you mark this as duplicate as string interpolation in JavaScript please read the question carefully, because I already read the other interpolation question for JavaScript but not one of them is have the same way that I want for my code (I tell the reason on the question), and I don't want to use Plugin.
Hi all, first I want you to know about my purpose in this code, you can tell this main reason is to build Query Binding for Express with MySQL, but I will use this code for other reason also.
I want to know about string interpolation in Javascript / Typescript that will work like Query Binding in code in Code Igniter source
// Code 1
let person = 'ujang'
let age = 23
console.log("Hello, %s. You're age is %d years old.", person, age)
// Hello, ujang. You're age is 23 years old.
// The function is similiar to this code
// $sql = "insert into tbl_user (name, age, groupname) values (?, ?, ?)";
// $this->db->query($sql,array('codeigniter, 35, 'Group 1'));
As can you see in above code I use console.log and it's working as I want it, but because the console.log is void and not returning any value I can't use it in real condition.
// Code 2
const str = 'helow, %s. and you want %d piece of cake.?'
const name = 'ujang'
const want = 13
const myFunction = (value, ...optionalParams) => {
// The function I want is similiar with Query Binding in Code Igniter
// And it can handle dynamicly params
// This only sample
value = value.replace('%s', optionalParams[0])
value = value.replace('%d', optionalParams[1])
return value
}
myFunction(str, name, want)
// helow, ujang. and you want 13 piece of cake.?
In Code 2 I'll try making a function, that working as expected, but only for static params.
// Code 3
const names = 'ujang'
const arg1 = 'good'
const argN = 'better'
const dontWantFunction = (value, arg1, argN) => {
return `helow, ${value}, this function is ${arg1} but any ${argN} solution.?`
}
dontWantFunction(names, arg1, argN)
// helow, ujang, this function is good but any better solution.?
In Code 3 is function that I don't really want, because is hard to manage and have more hardcode text inside the function.
Is anyone know how to fill myFunction in Code 2.?
or anyone working on similar code.?
or know some documentation / article that will lead me to this solution.?
I'am waiting for your response that will help me a lot,
Thank you for attention.
You can try something like this, where we take out the values from optionalParams in sequential manner and replace on matching value
const str = 'helow, {{value}}. and you want {{value}} piece of cake.?'
const name = 'ujang'
const want = 13
const myFunction = (value, ...optionalParams) => {
return value.replace(/\{\{value\}\}/g, (m) => optionalParams.shift() || m)
}
console.log(myFunction(str, name, want))

Pick out words in a string that are in array

I have spent hours, close to 8 hours none stop on this, I am trying to use jQuery/JS to create two arrays, one which is dynamic as it is loading a chat script and will be split by whitespace in to an array, for example:
String: Hello my name is Peter
Converted to (message) array: ['hello','my','name','is','peter'];
I have a set array to look out for specific words, in this example let us use:
(find array) ['hello','peter'] however, this array is going to contain up to 20 elements and I need to ensure it searches the message array efficiently, please help.
I can help you with that.
var arrayOfWords = $(".echat-shared-chat-message-body").last().text().split(" ");
That code is actually working! i went to an open chat in this website so I can tested.
So just replace the word REPLACE with your DOM object :)
var arrayOfWords = $("REPLACE").last().text().split(" ");
If I understood well, you're asking to filter an array of string (from an incoming string) given a second array.
In your described case you'll certainly not have to worry about efficiency, really. Unless your incoming message is allowed to be very very big.
Given that, there is a dozen of options, I think this is the most succinct:
const whitelist = [
'hello',
'peter'
]
const message = 'hello my name is Peter'.split(' ')
const found = message.filter(function(word) {
return whitelist.indexOf(word) > -1
}
You can treat invariant case:
const whitelistLower = whitelist.toLowerCase()
const foundInvariantCase = message.filter(function(word) {
return whitelist.indexOf(word.toLowerCase()) > -1
}
Or use ESS Set:
const whitelistSet = new Set(whitelist)
const found = message.filter(function(word) {
return whitelistSet.has(word)
}

JavaScript RegExp method exec() returns only one item [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Regex exec only returning first match
"a1b2c3d".replace(/[0-9]/g,"x")
returns "axbxdxd" as expected.
/[0-9]/g.exec("a1b2c3d")
however only returns an array containing one item: ["1"]. Shouldn't it return all matches?
Thanks in advance!
No. You need to call exec multiple times:
var re = /[0-9]/g;
var input = "a1b2c3d";
var myArray;
while ((myArray = re.exec(input)) != null)
{
var msg = "Found " + myArray[0] + ". ";
print(msg);
}
Edit: The Mozilla Developer Network page on exec has much more to say about this function. That's where I got the example and modified it for your question.
Edit 2: I've changed the above code so it isn't actually an infinite loop. :-)

Categories