I have few testcases names which I need to extract. The initial part will be the testcase id and next will be the description. I need to extract the id. For example
TC-ABC-98.1.010_1-Verify the layout credit page
TC-RegPMP-1.1.001_2-Verify the [MangerDetails] link is not displayed Admin Page - Name entered
TC-CS8 Customer solution-1.1.001_1-Verify all customer details are shown correctly
TC-USer Review-003-Scenario 1 - Verify User Review Page (User Review section)
Above are the titles, and the output I am expecting are :
TC-ABC-98.1.010_1
TC-RegPMP-1.1.001_2
TC-CS8 Customer solution-1.1.001_1
TC-USer Review-003-Scenario 1
The Solution i tried awas - /TC-(.*)-/g" But didnt worked. Can anyone please help
const sections = [
'TC-ABC-98.1.010_1-Verify the layout credit page',
'TC-RegPMP-1.1.001_2-Verify the [MangerDetails] link is not displayed Admin Page - Name entered',
'TC-CS8 Customer solution-1.1.001_1-Verify all customer details are shown correctly',
'TC-USer Review-003-Scenario 1 - Verify User Review Page (User Review section)'
];
const extract = (section) =>
section.match(/^(TC-.+)\s*-\s*(?=Verify)/)?.[1].trim() ?? null;
const extractAll = (sections) => sections.map(extract);
console.log(extractAll(sections));
The following returns:
[
"TC-ABC-98.1.010_1",
"TC-RegPMP-1.1.001_2",
"TC-CS8 Customer solution-1.1.001_1",
"TC-USer Review-003-Scenario 1"
]
This also works, and swaps "Verify" for any title-case word.
const sections = [
'TC-ABC-98.1.010_1-Verify the layout credit page',
'TC-RegPMP-1.1.001_2-Verify the [MangerDetails] link is not displayed Admin Page - Name entered',
'TC-CS8 Customer solution-1.1.001_1-Verify all customer details are shown correctly',
'TC-USer Review-003-Scenario 1 - Verify User Review Page (User Review section)'
];
const extract = (section) =>
section.match(/^(TC-.+)-(?:|\s-\s)(?=[A-Z][a-z]+)/)?.[1] ?? null
const extractAll = (sections) => sections.map(extract);
console.log(extractAll(sections));
You could use capture the part before -Verify in a group, and then match -Verify after it:
^(TC-.*?)\s*-\s*Verify\b
Explanation
^ Start of string
(TC-.*?) Capture group 1, match TC- followed by any char, as few as possible
\s*-\s* Match - between optional whitspace chars
Verify\b Match the word Verify
See a regex101 demo.
const regex = /^(TC-.*?)\s*-\s*Verify\b/gm;
const s = `TC-ABC-98.1.010_1-Verify the layout credit page
TC-RegPMP-1.1.001_2-Verify the [MangerDetails] link is not displayed Admin Page - Name entered
TC-CS8 Customer solution-1.1.001_1-Verify all customer details are shown correctly
TC-USer Review-003-Scenario 1 - Verify User Review Page (User Review section)`;
const res = Array.from(s.matchAll(regex), m => m[1]);
console.log(res);
Related
I'm trying to filter this
Alert me when this account’s current balance goes above $1.
from the list here:
alertTypes = [
'Alert me when this account’s available balance goes below $1.',
'Alert me when this account’s current balance goes below $1.',
'Alert me when this account’s available balance goes above $1.',
'Alert me when this account’s current balance goes above $1.']
Using this async function
const alertRegEx = "/.*current balance.*above.*/"
const alert = alertTypes.filter(alert => alert.match(alertRegEx))
But im getting the whole list in alert variable. What's my mistake here?
Firstly, do not use async in this case as match is not an async function (but even if it was you would not be able to use it in a filter). Then you need to use an literal regular expression,not a string.
And a minor, non-required, change is that you can skip the initial and final .*
const alertTypes = [
'Alert me when this account’s available balance goes below $1.',
'Alert me when this account’s current balance goes below $1.',
'Alert me when this account’s available balance goes above $1.',
'Alert me when this account’s current balance goes above $1.']
const alertRegEx = /current balance.*above/;
const alerts = alertTypes.filter( alert => alert.match(alertRegEx))
console.log(alerts);
I have a profile field where the data comes in the below format for each user profile.
User1 could have his profile field populated as below while user2 could have just one role/id/company listed in their profile.
RoleA : 123456 - company1 \n
RoleB : 234567 - company2 \n
RoleC : 891011
I am supposed to split the roles for each user into 1 field separated by commas and the id/company into another field separated by comma.
For the above data, the output should look like-
Role field - RoleA, RoleB, RoleC
ID/Company field - 123456-company1, 234567-company2.
This has to be done in JavaScript. Any suggestion is appreciated.
Thanks!
What you should do is something similar to below:
function splitProfile(profile, roleList, idCompanyList) {
var splitProfileString = profile.split(" : ");
roleList.push(splitProfileString[0]);
var splitIdCompanyString = splitProfileString[1].split(" - ");
// check if there is a company for `id`
if(splitIdCompanyString[1]) {
idCompanyList.push(splitIdCompanyString[0] + "-" + splitIdCompanyString[1].replace(" \n", ""));
}
}
var roleIdCompanyList = [
"RoleA : 123456 - company1 \n",
"RoleB : 234567 - company2 \n",
"RoleC : 891011"
];
var roleList = [];
var idCompanyList = [];
roleIdCompanyList.forEach(function(roleIdCompany) {
splitProfile(roleIdCompany, roleList, idCompanyList);
});
console.log(roleList.join(", ")); // RoleA, RoleB, RoleC
console.log(idCompanyList.join(", ")); // 123456-company1, 234567-company2
I tried to think that the input and the output are exactly similar to the ones you provided in the question. In any case, I hope you get the idea of what I am trying to do here.
I need a code showing user's server join position. For example:
User: !userinfo
Bot: You're 23rd member of server.
Here is a very basic example. I've tried to explain it with comments as much as I can.
// Import the Client class from Discord.js
const {Client} = require('discord.js')
// Initialise a new client
const client = new Client()
// This will be used later on to determine the ordinal suffix to use
// for 1st, 2nd, and 3rd
const digitToOrdinalSuffix = {
1: 'st',
2: 'nd',
3: 'rd'
}
// Add a listener for the 'message' event (which is emitted when a message is
// sent)
// The {author, channel, content, guild} destructures the message object.
// author is the message's author, channel is the message's channel etc.
client.on('message', async ({author, channel, content, guild}) => {
try {
// If the message content is '!userinfo'...
if (content === '!userinfo') {
// Send a message if it's a DM
if (!guild) return await channel.send('This command can’t be used in DMs!')
// This is the actual part that gets the user's 'join position'
// Get the message server's members...
const result = guild.members.cache
// sort them in ascending order by when they joined...
.sorted((a, b) => a.joinedAt - b.joinedAt)
// convert the Collection to an array so we can use findIndex...
.array()
// and find the position of the member in the array.
// For example, the first member to join the server will be the first
// member of the array (index 0), so they will be the
// 0 + 1 = 1st member to join.
.findIndex(member => member.id === author.id) + 1
// The last digit of the result (0-9)
const lastDigit = result % 10
// The last 2 digits of the result (0-99)
const last2Digits = result % 100
// Send the message
await channel.send(
`You’re the ${result}${
// 4th, 5th, 6th, 7th, 8th, 9th, 10th, 14th, 15th...
lastDigit === 0 || lastDigit > 3 ||
// 11th, 12th, 13th
last2Digits >= 11 && last2Digits <= 13
? 'th'
// 1st, 2nd, 3rd, 21st, 22nd, 23rd...
: digitToOrdinalSuffix[lastDigit]
} member of the server.`
)
}
} catch (error) {
// Log any errors
console.error(error)
}
})
// Login to Discord using your bot token. It is highly recommended that you don't
// literally put your token here as a string; store it somewhere else like a
// config or .env file.
client.login('your token')
If you are planning on adding a lot more commands, I recommend using a better command handler that trims the user input and handles arguments, instead of using if/else if to check if the input matches a string. A good example of this is on the Discord.js guide, which is a very good resource for learning how to code a bot using Discord.js.
I need to be able to convert a string (IP address) such as this 10.120.0.1 to a string (ISIS Network ID) such as this 49.0001.0101.2000.0001.00. The middle section 010 1.20 00.0 001 corresponds to the first string (I've spaced them out to show the IP address is inside it). You can see that there are 4 digits in each ISIS Network ID hextet that need to correspond to 3 digits in the IP Address octet. A number of 53 for example would have a leading 0 to make 3 digits.
All the IP addresses start with 10.120. so I just need to inject the last 2 octets from the IP Address into the ISIS Network ID.
I need this to be dynamic so when someone types in another ip address into a loopbackIP input, it automatically updates the isisNetworkID field.
I have this:
49.0001.0101.{{ isisNetworkID }}.00
This needs to take the value from an input v-model="loopbackIP" that I have and translate the remaining values to sit in the middle of that isisNetworkID following this format - xxxx.xxxx.
I've got this computed calculation but I'm not sure how to make 4 digits equal 3...
const loopbackIP = '10.120.0.1';
const isisNetworkID = computed(() => {
let idaho = '10.120.';
if (loopbackIP.indexOf(idaho)) {
return loopbackIP.slice(7);
} else {
console.log('Nothing is happening');
}
});
I hope this makes sense...
I think I understand what you're trying to achieve. Let's break it down into digestible parts. You have an IP address of:
10.120.0.1
And you want to transform it such that each part is padded to 3 digits:
['010', '120', '000', '001']
This can be done by splitting the string by the . character, and the using String.prototype.padStart(). We then join the array back into a string:
'010120000001'
||||
^^^^ -> to be deleted
We know that the first 4 digits is not needed, since it's already part of your template, so we can remove them using String.prototype.substring(4). That leaves us with:
'20000001'
Now it is just the matter of splitting it into 4 characters per item:
['2000', '0001']
...and rejoining it with . character:
'2000.0001'
...and interpolating it back into the string. I have a proof-of-concept example below, which should output the desired string:
const loopbackIP = '10.120.0.1';
const parts = loopbackIP.split('.').map(x => x.padStart(3, '0'));
// Remove the first 4 characters
let isisNetworkId = parts.join('');
isisNetworkId = isisNetworkId.substring(4);
const output = `49.0001.0101.${isisNetworkId.match(/.{4}/g).join('.')}.00`;
console.log(output);
So if you want to translate it to your VueJS code, it should look no different that this:
const loopbackIP = '10.120.0.1';
const isisNetworkID = computed(() => {
const loopbackIP = '10.120.0.1';
const parts = loopbackIP.split('.').map(x => x.padStart(3, '0'));
let isisNetworkId = parts.join('');
isisNetworkId = isisNetworkId.substring(4);
// Rejoin, split into items of 4-character long, rejoin by period
return isisNetworkId.match(/.{4}/g).join('.');
});
I have a post that contains a content body, the text in content body need to be properly formatted.
If the content contain a special keyword #, # i want to convert it to a usefull link.
content = "These is a sample post it can contain any thing and i can mention people with #username and show hastag reference #stackoverflowQuestion";
newContent = content.split(" ");
username = [];
hashtag = [];
newContent.forEach((sub) => {
at = sub.indexOf("#");
tag = sub.indexOf("#");
if(at == 0){
trendname.push(sub)
}
if(tag == 0){
hashtag.push(sub)
}
return sub;
});
username.forEach((user) => {
user.link = user.replace(/#/, "/${user}");console.log(user.link);
return user;}); console.log(user.link);
hashtag.forEach((str) => {
str.taged= str.replace(/([a-z])([A-Z])/g, '$1 $2').toLowercase;
return str;}); console.log(str.taged);
Firstly the code above is not loging vakue outside the loop.
Secondly is there any other way to re-write these sode because it look in efficient. if there is Please specify.
Thanks
your question is a little bit complicated to understand I think... But anyways I hope the following will help you somehow.
First, you can simplify your first loop to:
let usernames = content.match(/#([^ ]*)/g)
let hashtags = content.match(/#([^ ]*)/g)
Those are regex, and they work as follow:
They begin with # or # (if you are looking for usernames or hashtags)
[^ ]* means "Everything but a white space, and multiple times (*)
So now, you can construct user objects:
let users = usernames.map(username => {
return {
username: username,
link: '/' + username.slice(1, username.length)
}
}) // --> [ { username: '#username', link: '/username' } ]
Here is the complete code I wrote:
let content = "These is a sample post it can contain any thing and i can mention people with #username and show hastag reference #stackoverflowQuestion";
let usernames = content.match(/#([^ ]*)/g)
let hashtags = content.match(/#([^ ]*)/g)
let users = usernames.map(username => {
return {
username: username,
link: '/' + username.slice(1, username.length)
}
})
console.log(users)
Something is wrong with your code. You are making a forEach on an array of strings, and then you try to set a property to that string: user.link = ....
Secondly, you are trying to log values outside of your loops, and doing so puts you out of the scope of the loop. So you can't log those variables and this is completely normal because they just don't exist anymore... Try to indent your code better, you'll see it directly.
Hope this helps, and try working a little bit on the redaction of your questions, the stack overflow community can be harsh some times