I was advised to use regex with this discord.js project. It saves two mentions from a message into two variables in the order the two mentions are typed. Discord.js reads mentions in the numeric order of the actual IDs, not the actual typed order, so we have to use regex instead. The command string is: f$command #user1 #user2
So, here's my code:
else if (command === 'command'){
const regex = /<#!?(\d+)>/;
let match = regex.exec(message);
while (match){
const User1 = match[1].id;
const User2 = match[2].id;
}
Is this correct, and how do I make it require 2 regex matches?
else if (command === 'command') {
const regex = /<#!?(\d+)>/;
let match = regex.exec(message);
const result = [];
while (match){
result.push(match[1]);
match = regex.exec(message);
}
if (result.length !== 2) {
console.error('not 2 matches');
}
const User1 = result[0];
const User2 = result[1];
}
Related
I have a string query
const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
I want to store the words inside "NOT" block in an array.
What could be the most effective approach for this?
Expected result - ["app", "agency"]
We can use match(), twice:
const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
var terms = query.match(/\bNOT\s*\((.*?)\)/)[1]
.match(/\w+/g)
.filter(x => x !== "OR" && x !== "AND");
console.log(terms);
const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
function useRegex(input) {
let regex = /\(([a-zA-Z]+( [a-zA-Z]+)+)\) NOT \(([a-zA-Z]+( [a-zA-Z]+)+)\) ([A-Za-z0-9]+( [A-Za-z0-9]+)+)/i;
return input.match(regex);
}
console.log(useRegex(query)[3]);
Step 1: Split the query before and after NOT keyword using query.split('NOT')
-> Here only data after NOT is needed so we can use, query.split('NOT')[1]
Step 2: Use regex rx.exec(res)[1] to get the value in between the paranthesis.
Step 3: Get the values before and after OR.
const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
const res = query.split('NOT')[1];
const rx = /\(([^)]+)\)/;
const result = rx.exec(res)[1].split(' OR ');
console.log(result);
I'm trying to check if there is one or more words in a url, how could I proceed?
I'm trying to check if a url has in it the category that a product has
I tried like this
const url = "http:/localhost/fast-food-ham/hotdog.html";
const words = "Fast Food";
console.log(
url.toLowerCase().includes(words.toLowerCase())
);
You can use Regular Expressions.
const url = "http:/localhost/fast-food-ham/hotdog.html";
const words = /fast(-|\s)food/i;
if(url.match(words)) {
console.log(true);
} else {
console.log(false);
}
The above code prints true if the url contains fast food or fast-food; false otherwise.
If you need to print true if is there a character that is not a space between fast and food (eg: fast+food, fast_food) you can add \S for the captures in the regular expression:
const words = /fast(-|\s|\S)/i
The last /i means that the case of the text is ignoring. Since that you don't have to url.toLowerCase().
Learn more about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Hope this helps.
you can split the string to words:
const url = "http:/localhost/fast-food-ham/hotdog.html";
const words = "Fast Food";
words_lst=words.split(" ");
let isexist=false;
for (let word of words_lst)
if(url.toLowerCase().includes(word.toLowerCase())){
isexist=true;
break;
}
console.log(isexist)
have fun :)
you can try this code
let text = "http:/localhost/fast-food-ham/hotdog.html";
let words = "Fast Food";
let a = words.replace(/ /g,"-").toLowerCase();
var regex = new RegExp( a, 'i' );
let result = text.match(regex);
If you want to check if something is true or false, you will need to use an if statement. keep in mind that includes is case-sensetive.
// to check url as a given variable
const url = "http:/localhost/fast-food-ham/hotdog.html";
if (url.includes("fast-food")) {
console.log("Yes");
} else {
console.log("No");
}
// to check current page URL
const currentURL = location.href;
if (currentURL.includes("html")) {
console.log("Yes");
} else {
console.log("No");
}
// to check if it includes one of multiple words in current page URL
if (currentURL.includes("css" && "gg" && "stack")) {
console.log("Yes");
} else {
console.log("No");
}
// to check if it includes multiple words in current page URL
if (currentURL.includes("stack" || ".com")) {
console.log("Yes");
} else {
console.log("No");
}
I am working on aws project which consist of VTL(Velocity template language) library and graphql schema. The database is also of aws particularly dynamodb. Now Its sending(mutation) data to db through "\". I wanted to know what does the meaning of "\"?
mutations.forEach((mutation) => {
let details = `\\\"id\\\": \\\"$ctx.args.id\\\"`;
if (mutation === "addLolly") {
//details = `\\\"color1\\\":\\\"$ctx.args.lolly.color1\\\" , \\\"color2\\\":\\\"$ctx.args.lolly.color2\\\", \\\"color3\\\":\\\"$ctx.args.lolly.color3\\\", \\\"sender\\\":\\\"$ctx.args.lolly.sender\\\", \\\"reciever\\\":\\\"$ctx.args.lolly.reciever\\\", \\\"message\\\":\\\"$ctx.args.lolly.message\\\", \\\"link\\\":\\\"$ctx.args.lolly.link\\\"`;
details = `\\\"color1\\\":\\\"$ctx.args.lolly.color1\\\" , \\\"color2\\\":\\\"$ctx.args.lolly.color2\\\" , \\\"color3\\\":\\\"$ctx.args.lolly.color3\\\" ,\\\"reciever\\\":\\\"$ctx.args.lolly.reciever\\\" ,\\\"sender\\\":\\\"$ctx.args.lolly.sender\\\" , \\\"message\\\":\\\"$ctx.args.lolly.message\\\" , \\\"link\\\":\\\"$ctx.args.lolly.link\\\"`;
}
We have to add an extra backslash to a backslash in a string to escape them.
const str2 = '\\'; // is valid = 1 backslash
const str1 = '\'; // is invalid = error
const str3 = '\\\'; // is therefore invalid = error
const str6 = '\\\\\\'; // is valid = 3 backslashes
I'm using named capturing groups to validate and extract data out of a product number. The format of the product number looks like this:
1102961D048.075
Chars 1-2 gender_code 11
Chars 1-6 style 110296
Chars 7-8 width_code 1D
Chars 9-11 color_code 048
Char 12 delimiter ignored
Chars 13-15 size_code 075
My current code looks like this:
const validateMpn = (mpn) => {
const regex = /(?<style>\d{6})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
const match = regex.exec(mpn)
if (!match) {
return null
}
return match.groups
}
const str1 = '1102961D048.075'
const str2 = '1200322A001.085'
const match1 = validateMpn(str1)
const match2 = validateMpn(str2)
console.log(match1)
console.log(match2)
As gender_code and style overlap I'm not sure how to get them both. Therefore I have the following questions:
Is it possible to this with only one regular expression?
If yes, how could I accomplish this?
Sure, just place gender inside the style group:
const validateMpn = (mpn) => {
const regex = /(?<style>(?<gender>\d{2})\d{4})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
const match = regex.exec(mpn)
if (!match) {
return null
}
return match.groups
}
const str1 = '1102961D048.075'
const str2 = '1200322A001.085'
const match1 = validateMpn(str1)
const match2 = validateMpn(str2)
console.log(match1)
console.log(match2)
I suggest just having separate capture groups for the first two and four following characters. Then, form the style by just concatenating together the first two capture groups:
var input = "1102961D048.075";
var regex = /(.{2})(.{4})(.{2})(.{3}).(.{3})/g;
var match = regex.exec(input);
console.log("gender_code: " + match[1]);
console.log("style: " + match[1] + match[2]);
As a style note, I prefer not using named capture groups, because they tend to result in a bloated regex which is hard to read.
Yes you can capture gender_code using positive look ahead using this regex,
(?=(..))(\d{6})(\d{1}[ABDE])(\d{3})\.(\d{3})
Regex Demo
This is named groups regex but will only work in Chrome browser
and named capture grouping will be available in ECMAScript 2018 and is only supported in Chrome as of now.
This JS demo will work in Chrome as that is the only one as of now supporting EcmaScript2018,
const validateMpn = (mpn) => {
const regex = /(?=(?<gender_code>\d\d))(?<style>\d{6})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
const match = regex.exec(mpn)
if (!match) {
return null
}
return match.groups
}
const str1 = '1102961D048.075'
const str2 = '1200322A001.085'
const match1 = validateMpn(str1)
const match2 = validateMpn(str2)
console.log(match1)
console.log(match2)
Take these two urls:
const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'
Is there a solution to match these two urls and return true as they are similar?
I tried the following and should be the worst solution:
const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'
const split1 = url1.split('/')
const split2 = url2.split('/')
let matchCount = 0
let notMatchedCount = 0
split1.map(x => {
if(x === split2[x]) {
matchCount++
} else {
notMatchedCount++
}
})
if(matchCount > notMatchedCount) {
console.log('Match Found')
} else {
console.log('Match not found')
}
EDIT
Solution was to use PathToRegExp package! Thanks to #ChiragRavindra!
You could use a regex to test the url
\/user\/ matching /user/
\w+ matching 1 or more word characters ([a-zA-Z0-9_]+)
\/edit matching /edit
const url1 = '/user/{username}/edit';
const urlCorrect = '/user/harry/edit';
const urlWrong = '/users/harry/edit';
//generate a regex string by escaping the slashes and changing word between curly brackets with {\w+}
var regexString = url1.replace(/\{\w+\}/g, '\\w+').replace(/\//g, '\\/');
console.log('generating regex: ' + regexString);
var regex = new RegExp(regexString);
//test using the generated regex
console.log(regex.test(urlCorrect));
console.log(regex.test(urlWrong));
I would suggest you to look inside this library
NPM - String similarity library
Library simply returns the probability of comparing two strings if they're similar.
Then it's all on you to set up the threshold from how many percentages you assume that they're the same.