Extract optional arguments / parameters from a string - javascript

Lets say I have the following string, which I may receive and require my program to act up on:
ACTION -F filter string -L location string -M message string
How can I reliably extract the 'arguments' from this string, all of which are optional to the user?
I spent a lot of time instead writing ACTION, filter, location, message and using .split(", ") to put the args to an array but found this too difficult to work reliably.
var content = req.body.Body.split(", "); // [ Type, Filter, Location, Message]
var msgType = content[0].trim().toUpperCase();
if (msgType === 'INFO') {
// return info based on remainder of parameters
var filterGroup = content[1].trim();
var destination = content[2].trim();
var message = '';
// The message may be split further if it is written
// with a ',' so concat them back together.
if (content.length > 2) { // Optional message exists
// Message may be written in content[3] > content[n]
// depending how many ', ' were written in the message.
for (var i = 3; i < content.length; i++) {
message += content[i] + ", ";
}
}
}
Is the -a argument format even the best way? Much googling returns information on extracting the arguments used to run a nodeJS program, but that isn't applicable here, as the program is already running and the string not used at runtime. I'm at the design stage so have complete control over the format of the user input, but they're sending a SMS with these commands so the simpler the better!
I'm writing in javascript and would appreciate your thoughts

You can use a regex to match the -X pattern and then use a loop to extract the strings between each pattern match.
The regex here is /(?<=\s)\-[A-Za-z](?=\s)/g, which looks for a dash followed by a letter with a white space character on either side.
const input = "ACTION -F filter string -L location string -M message string";
let regex = /(?<=\s)\-[A-Za-z](?=\s)/g;
let args = [];
while(match = regex.exec(input))
{
args.push(match);
}
let solved = [];
for(let i = 0; i < args.length; i++)
{
let cmd = args[i][0];
let idx = args[i].index;
let val;
if(i + 1 == args.length)
val = input.substr(idx + cmd.length + 1);
else
val = input.substring(idx + cmd.length + 1, args[i + 1].index - 1);
solved.push({
cmd: cmd,
val: val
});
}
console.log(solved);

Related

DOMException while copying text to clipboard in javascript

I am trying to make a simple encoder in javascript, and copying the output to the clipboard, but the code gives an error.
I tried this code:
function encode() {
let alphabet = " abcdefghijklmnopqrstuvwxyz1234567890-=!##$%^&*()_+[];'/.,'{}|:~";
const a_list = alphabet.split('');
const m_list = prompt("message: ").split('');
let return_message = "";
for (let i = 0; i < m_list.length; i++) {
let current_letter = m_list[i];
let translated_letter = a_list[a_list.indexOf(current_letter) + 5];
return_message += translated_letter;
}
navigator.clipboard.writeText(return_message);
}
encode()
but the console gives this error:
Error: DOMException {INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, …}
I host the server in replit.
When I try to do an alert with the encoded words, it works fine.
navigator.clipboard.writeText requires a transient user activation. That is why it works when you click on an alert box.
Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.
The "clipboard-write" permission of the Permissions API is granted automatically to pages when they are in the active tab.
https://devdocs.io/dom/clipboard/writetext
The error you are getting is because the indexOf function returns -1 when the sought character is not found in the a_list array.
You can check whether the index returned by indexOf is greater than or equal to zero before accessing the element in the a_list array. If the index returned is less than zero, you can simply add the original character to return_message.
Here is an example:
function encode() {
// Define the list of characters to be substituted
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const charList = alphabet.split('');
// Receive the string to be substituted from the user
const inputString = prompt("Enter the string to be substituted:");
// Convert the string to an array of characters
const inputChars = inputString.split('');
// Create a new array with the substituted characters
const outputChars = inputChars.map(char => {
// Find the index of the current character in the character list
const index = charList.indexOf(char.toLowerCase());
// If the character is not in the character list, keep the original character
if (index === -1) {
return char;
}
// Find the next character in the character list
const nextIndex = (index + 1) % charList.length;
const nextChar = charList[nextIndex];
// Return the next substituted character
return char.toUpperCase() === char ? nextChar.toUpperCase() : nextChar;
});
// Convert the array of characters back to a string
const outputString = outputChars.join('');
// Display the substituted string in the console
navigator.clipboard.writeText(outputString);
}
encode()
And as answered in #dotnetCarpenter reply navigator.clipboard.writeText requires a transient user activation. That's why it works when an alert box is clicked.

How do I mask an email address between the first and the last character before the # sign?

My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe#abc.com then I should output j*****e#abc.com.
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first[i] = '*';
}
ans = first +"#" +parts[1];
}else{
}
return ans;
};
However in my loop I can't change the characters to asterisks.
After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?
To answer your question... javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)
You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...
Well, this's what you're looking for, and this will be the output j*****e#abc.com.
var ans = "";
var S = "johndoe#abc.com"; //example
S = S.toLowerCase();
var parts = S.split("#");
var first = "";
for(var i = 0; i < parts[0].length; i++){
if(i != 0 && i != parts[0].length - 1){
first += '*';
}else{
first += parts[0][i];
}
}
ans = first +"#"+ parts[1];
console.log(ans);
Here is the code with your approach:
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0][0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first += '*';
}
ans = first + parts[0][parts[0].length - 1] +"#" +parts[1];
}else{
}
return ans;
};
But if i were you i would use:
var mail = "johndoe#abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.#)/gi, '*'.repeat(mail.split('#')[0].length - 2));
console.log(mail);
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.
Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)
I would use this code:
function maskPII(str) {
const indexOfAt = str.indexOf('#');
if (indexOfAt <= 2) {
return str;
}
return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}
const email = 'johndoe#abc.com';
console.log(email);
console.log(maskPII(email));
It will look for the index of the # sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.
Otherwise it will get the first character, calculate the amount of asterisks needed (index of the # sign -2) and repeat those and then add the rest of the original string.

String.split function is not working properly with some text

I have string parser in node.js. Input string comes from telegram channel.
Now I have serious problem with String.split function.
It works with some types of text but it doesn't work with some other texts.
When I receive not processed string in telegram, I just copy and send it in the channel again.
In this case, parser processes it well.
Is there any advise for this issue?
let teams = [];
teamSeps =[" vs ", " v ", " - ", " x " ,"-", " -"];
for(let i = 0; i< teamSeps.length; i++){
teams = newTip.Match.toLowerCase().split(teamSeps[i]);
if(teams.length === 2) break;
}
newTip.Home = teams[0].trim();
newTip.Away = teams[1].trim();
return;
Instead of adding multiple options with optional spaces on either side of -, you can use a single regex with some alternation.
/\s*-\s*|\s+(?:vs|v|x)\s+/
\s*-\s*: Allows optional space around -
\s+(?:vs|v|x)\s+: Allows at least one space around vs or v or x (Otherwise, if there is a x or v in the string, it will split)
function customSplit(str) {
return str.split(/\s*-\s*|\s+(?:vs|v|x)\s+/);
}
console.log(customSplit("Man United vs Man City"))
console.log(customSplit("France - Croatia"))
console.log(customSplit("Belgium-England"))
console.log(customSplit("Liverpool x Spurs"))

Check first x number of letters of a string

Is there a simple way to check if a string in JavaScript matches a certain thing for example:
Lets say the you wanted to check for the first word which had:
/admin this is a message
Then using JS to look for /admin so that I can direct the message in my chat window??
One way would be to use indexOf() to see if /admin is at pos 0.
var msg = "/admin this is a message";
var n = msg.indexOf("/admin");
If n = 0, then you know /admin was at the start of the message.
If the string does not exist in the message, n would equal -1.
Or,
string.match(/^\/admin/)
According to http://jsperf.com/matching-initial-substring, this is up to two times faster than either indexOf or slice in the case that there is no match, but slower when there is a match. So if you expect to mainly have non-matches, this is faster, it would appear.
To achieve this, you could look for a "special command character" / and if found, get the text until next whitespace/end of line, check this against your list of commands and if there is a match, do some special action
var msg = "/admin this is a message", command, i;
if (msg.charAt(0) === '/') { // special
i = msg.indexOf(' ', 1);
i===-1 ? i = msg.length : i; // end of line if no space
command = msg.slice(1, i); // command (this case "admin")
if (command === 'admin') {
msg = msg.slice(i+1); // rest of message
// .. etc
} /* else if (command === foo) {
} */ else {
// warn about unknown command
}
} else {
// treat as normal message
}
You could use Array.slice(beg, end):
var message = '/admin this is a message';
if (message.slice(0, 6) === '/admin') {
var adminMessage = message.slice(6).trim();
// Now do something with the "adminMessage".
}

problem in fetching a particular cookie

This is the script that i am using to fetch a particular cookie lastvisit :
AFTER THE EDIT
// This document writes a cookie
// called from index.php
window.onload = makeLastVisitCookie;
function makeLastVisitCookie() {
var now = new Date();
var last = new Date();
now.setFullYear(2020);
// set the cookie
document.cookie = "lastvisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
var allCookies = document.cookie.split(";");
for( var i=0 ; i < allCookies.length ; i++ ) {
if(allCookies[i].split("=")[0]== "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited this site on" + allCookies[i].split("=")[1];
} else {
alert("testing..testing..");
}
}
}
From this script the if part never works though there are 5 cookies stored from my website. (including the cookie that i am saving from this script) What is the mistake that i am making while fetching the cookie named lastvisit ?
You're splitting the cookie by ; an comparing those tokens with lastvisit. You need to split such a token by = first. allCookies[i] looks like key=val and will never equal lastvisit. Een if allCookies[i] == "lastvisit" is true, the result will still not be as expected since you're showing the value of allCookies[i + 1] which would be this=the_cookie_after_lastvisit.
if(allCookies[i].split("=") == "lastvisit") { should be:
var pair = allCookies[i].split("=", 2);
if (pair[0].replace(/^ +/, "") == "lastvisit") {
"You visited this site on" + allCookies[i+1]; should be:
"You visited this site on" + pair[1];
The 2 argument of split makes cookies like sum=1+1=2 be read correctly. When splitting cookies by ;, the key may contain a leading space which much be removed before comparing. (/^ +/ is a regular expression where ^ matches the beginning of a string and + one or more spaces.)
Alternatively, compare it directly against a RE for matching the optional spaces as well (* matches zero or more occurences of a space character, $ matches the end of a string):
if (/^ *lastvisit$/.test(pair[0])) {
I've tested several ways to get a cookie including using regular expressions and the below was the most correct one with best performance:
function getCookie(name) {
var cookie = "; " + document.cookie + ";";
var search = "; " + encodeURIComponent(name) + "=";
var value_start = cookie.indexOf(search);
if (value_start == -1) return "";
value_start += search.length;
var value_end = cookie.indexOf(';', value_start);
return decodeURIComponent(cookie.substring(value_start, value_end))
}
You need to remove possible white space around the cookie key before comparing to the string "lastvisit". This is done conveniently using regular expressions. /^\s+/ matches all white space at the beginning, /\s+$/ matches all white space at the end. The matches are replaced by the empty string, i.e. removed:
for( var i = 0 ; i < allCookies.length ; i++ ) {
var c = allCookies[i].split("="); // split only once
var key = c[0].replace(/^\s+/, '').replace (/\s+$/, ''); // remove blanks around key
if (key == "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited on " + c[1];
}
//...
}

Categories

Resources