How to take name and last name with match function? - javascript

You can add comment in my project and you can reply my comment. I want to take the name and surname after "#". How can I do that?
My find username function
const findUsername = message => {
var attachments = message.match(/#[^\s]+/g);
console.log(attachments);
return attachments !== null
? attachments.map(item => item).join('')
: null; };
This function just take the name, example: "#John Dao", function take the John. Anybody help me ?
Comment Example:
Comment
Reply Example:
Reply Example
Message argument example : "#Berkay Ergün skajjkdalskjdadsa"

You can try this:
const splitName = (name = '') => {
const res = name.substring(1)
const [firstName, ...lastName] = res.split(' ').filter(Boolean);
return {
name: firstName,
surname: lastName.join(' ')
}
}
console.log(splitName('#Jon Doe'));

Related

Execute promise or await with generated string variable

I am building a mongoose query and storing it in a variable call query. The code below shows it
let query = "Product.find(match)";
if (requestObject.query.sortBy) {
query = query.concat(".", "sort(sort)");
const parts = requestObject.query.sortBy.split(":");
sort[parts[0]] = parts[1] === "desc" ? -1 : 1;
}
if (requestObject.query.fields) {
query = query.concat(".", "select(fields)");
const fields = requestObject.query.fields.split(",").join(" ");
const items = await Product.find(match).sort(sort).select(fields); //.populate("category").exec();
/**const items = await Product.find(match).sort(sort).select("-__v"); //.populate("category").exec();**/
}
I am facing an issue when attempting to run a mongoose query that I have generated and stored in a string. When I run it in post man, the response is 200 but no data is returned. Below is a console.log(query) on line 2
what I hope to achieve is to have await or create a new promise execute the content id query variable like shown below
const items = new Promise((resolve) => resolve(query)); //.populate("category").exec();
items
? responseObject.status(200).json(items)
: responseObject
.status(400)
.json({ message: "Could not find products, please try again" });
I will appreciate it very much that and also if you can give me a better way of doing it, I will love that
This doesn't really make sense. You are building a string, not a query. You can't do anything with that string. (You could eval it, but you really shouldn't). Instead, build a query object!
let query = Product.find(match);
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {};
sort[field] = dir === "desc" ? -1 : 1;
query = query.sort(sort);
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
}
//query.populate("category")
const items = await query.exec();
if (items) {
responseObject.status(200).json(items)
} else {
responseObject.status(400).json({ message: "Could not find products, please try again" });
}
If you really want to get that string for something (e.g. debugging), build it separately from the query:
let query = Product.find(match);
let queryStr = 'Product.find(match)';
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {[field]: dir === "desc" ? -1 : 1};
query = query.sort(sort);
queryStr += `.sort(${JSON.stringify(sort)})`;
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
queryStr += `.select(${JSON.stringify(fields)})`;
}
//query.populate("category")
//queryStr += `.populate("category")`;
console.log(queryStr);
const items = await query.exec();
…

Swapping out Constants for a Function

I'm trying to refactor the following code, which depending on the top level domain of the recipients email, changes where you click through to in my button. I currently do this with two consts, which I need to refactor into only one.
const CCENTERURL_AT= `${HOSTURL_AT}/ccenter/zendesk/landing/`;
const CCENTERURL = `${HOSTURL}.com/ccenter/zendesk/landing/`;
const recipientEmail = data.ticket.recipient;
var cCenterUrl;
if(recipientEmail.indexOf(".com") > 0)
{
cCenterUrl = getCcenterUrl(zendeskID)
}else{
cCenterUrl = getAustrianCcenterUrl(zendeskID)
}
function getCcenterUrl(ticketID) {
const cCenterTicketUrl = CCENTERURL + ticketID ;
return cCenterTicketUrl;
}
// Get Austrian Ccenter Ticket Url using Zendesk ticket ID
function getAustrianCcenterUrl(ticketID) {
const cCenterTicketUrlAustria = CCENTERURL_AT + ticketID ;
return cCenterTicketUrlAustria;
}
I know I should be able to create a function which will take recipient Email`s top-level domain as parameter and return appropriate URL for CCENTERURL. But no matter what I've tried its become overcomplicated or hasn't worked. I would be interested to hear peoples opinions on either how I can achieve my goal or even how it would be better to go about this!
So you basically want to combine these into one function and use a string template like this.
const HOSTURL = 'example.com/'
const HOSTURL_AT = 'example.au/'
const reAu = /\.au$/;
const getTicketURL = (
(mail, id) => `${ reAu.test(mail) > 0 ? HOSTURL : HOSTURL_AT }ccenter/zendesk/landing/${id}`
);
// Test AU
console.log(getTicketURL('foo#google.com.au', 'ABC1231'))
// Test US
console.log(getTicketURL('foo#google.com', 'ABC1231'))

How can I separate Username and ID from command?

I made a code using the DankMemer Youtube Imgen API. When I type:
,youtube hello
, it displays:
But when I tag someone, it displays the text along with the ID:
Is there a way I can separate the username from the text?
let target = message.mentions.users.first() || message.author;
let profilepic = target.avatarURL;
let sentence = args.join(" ");
let url = ` https://dankmemer.services/api/youtube?avatar1=${profilepic}&username1=${target.username}&text=${sentence}`;
message.channel.startTyping();
snekfetch.get(url, {
headers: {
"Authorization": token
}
}).then(async res => {
await message.channel.send({
files: [{
attachment: res.body,
name: `${target.tag}-youtube.jpg`
}]
}).then(() => message.channel.stopTyping());
}).catch(err => console.error(err));
let sentence = args.join(" ");
you joined the args there which I think also includes the user mentioned. The only thing you need to do is remove the mention. If you want to remove only the first mention then do this-
if (!target === message.author) {
let toremove = `{#${target.id}}`;
sentence = sentence.replace(toremove, "");
}
Add this code after this line-
let sentence = args.join(" ");
You can replace all mentions in the message's content with blanks using regex, like so:
let messageContentWithoutMentions = message.content.replace(new RegExp("<#\d+>","gm"),"")
If you wanted to remove something else, just make use of the string.replace function.

How does one parent a channel to a category with a discord bot?

Basically there is no errors in the output but at the same time it's not doing what I'm trying to achieve.
Ive been tinkering with the script for 5 hours straight mixing up line positioning and now I got it to where it gives me the promise (my initial issue) but I cant parent the channel.
I've tried discord.js server and site, youtube, 2 other sites i forgot the name of but i cant crack it.
function setup(arguments, message){
var server = message.guild;
var name = message.author.username;
let searchquery = arguments.join("")
let cat = server.createChannel("Important", "category");
async function Channelmaker(Sent, obj){
try {
let chan = await server.createChannel(Sent, "Text");
//console.log(obj);
return chan
} catch(prom){
var chan2 = await server.createChannel(Sent, "Text");
return new Promise(resolve => {
var chan2 = server.createChannel(Sent, "Text", parent = obj);
resolve(chan2)
});
}
}
var holding
var chan = Channelmaker("⚖️ rules ⚖️", cat).then(value => {
console.log(value)
holding = value
value.parentID = cat
chan.setParent(cat.Id)
}).catch(error => {
// s
});
console.log("holding")
console.log(holding)
}
The category is not the parent of the "⚖️ rules ⚖️" channel that is created which is the opposite of what I'm trying to achieve
In Guild.createChannel(), use the options parameter including ChannelData, like so:
await server.createChannel(Sent, {
// You can omit the 'type' property; it's 'text' by default.
parent: obj
});

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

Categories

Resources