I'm trying to split a string from the second position in my string which I pass to the function.
Current position:
commandHandler(player: PlayerMp, command: string) {
if(command.startsWith("/", 0)){
const cmd = command.match(/\S+/g);
cmd.forEach(element => console.log(element));
}
}
If I pass "/test this" to this function then I get the following response: 1) "/test" 2) "this" while I need the following response: 1) "test" 2) "this"
What am I doing wrong?
You can use slice(1) to remove the first character of the string then proceed as before.
const command = "/test this";
if(command.startsWith("/")){
const cmd = command.slice(1).match(/\S+/g)
cmd.forEach(element => console.log(element));
}
Related
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.
So I have this code that would get the first string's from the right hand side and stop whenever there is an integer but for some reason its not working with me.
Example input of fUnit is "CS_25x2u"
expected output of it after using unit is "u".
Real output is "undefined".
function buildUnit(fUnit){// wahts ginna be passed here is the gibirish unit and the output of this function is the clear unit
fUnit = fUnit.toString;
const regex = /[a-zA-Z]*$/;
const unit = (x) => x.match(regex)[0];
fUnit = unit(fUnit);
If you need more info please let me know
Thank you
const regex = /[a-zA-Z]*$/;
console.log(regex.exec(sample));
Assuming fUnit variable contains your string
const unit = (x) => x.match(regex)[0];
console.log(unit(fUnit));
Just in case.
function buildUnit(fUnit) {
return fUnit.toString().match(/[A-z]*$/)[0];
}
console.log(buildUnit('CS_25x2u')); // 'u'
console.log(buildUnit('')); // ''
console.log(buildUnit(123)); // ''
console.log(buildUnit('aaa123')); // ''
console.log(buildUnit('aaa 123 bbb')); // 'bbb'
I have the following problem statement:
Write a function, uncompress, that takes in a string as an argument.
The input string will be formatted into multiple groups according to
the following pattern:
number + char
for example, '2c' or '3a'.
The function should return an uncompressed version of the string where
each 'char' of a group is repeated 'number' times consecutively. You
may assume that the input string is well-formed according to the
previously mentioned pattern.
test_00: uncompress("2c3a1t"); // -> 'ccaaat'
Here is my code which is using a stack. The problem is that it's only returning 'cc' and I can't figure out why. I've console logged what goes into the IF ELSE and I'm hitting both so I don't understand why nothing gets pushed to the stack.
Would really appreciate the help if someone can spot what I'm missing.
const uncompress = (s) => {
const nums = '23456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
const num = stack.pop();
stack.push(char.repeat(num));
};
};
return stack.join('');
};
console.log(uncompress("2c3a1t")); // -> 'ccaaat'
Here's how I would do it:
Split the string up into pairs of numbers and chars:
str.match(/\d+[a-zA-Z]/g)
And reduce that array to a string, while taking each value from the array, getting the char from it (cv.match(/[a-zA-Z]/)[0]) and repeating it according to the number (.repeat(parseInt(cv)))
const uncompress = str => str.match(/\d+[a-zA-Z]/g).reduce((acc, cv) =>
acc + cv.match(/[a-zA-Z]/)[0].repeat(parseInt(cv)), "")
console.log(uncompress("2c3a1t"))
console.log(uncompress("27b1d8g"))
And just like that I was able to write the code which passed the test case:
const nums = '123456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
let num = '';
while (nums.includes(stack[stack.length - 1])) {
num += stack.pop();
}
stack.push(char.repeat(num));
};
};
return stack.join('');
};
var login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.substring(0, login_id.lastIndexOf("#")));
Above script works perfectly if I pass input with '#abc.com'. Does not work if string do not have '#domain.com'
We have some user name with username#domain.com and few are just username. I want extract #domain.com from user name. Expected output is if input is username#domain.com return output = username and if input is username, output should be username.
Please help if there is any way.
Use .split() method to split your string in parts
It will still work if you do not have #domain.com
Case-1:
const login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
Case-2:
const login_id = 'sa-testaccount0125';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
If you split on # then you get an array of items. The first item of the array will be the username, whether there was a # in it or not.
const test = str => str.split('#')[0]
console.log(test('sa-testaccount0125#abc.com'));
console.log(test('sa-testaccount0125'));
You're already using a indexOf. Usee that to check # if exists as well:
function check(login_id) {
if (login_id.indexOf('#') >= 0) {
return login_id.substring(0, login_id.lastIndexOf("#"));
}
return login_id;
}
console.log(check('sa-testaccount0125#asdasdasd.com'));
console.log(check('sa-asd'));
console.log(check('sa-asasd#domain.com'));
check first if it contains the '#' charactar first
login_id.includes('#') ? console.log(login_id.substring(0,
login_id.lastIndexOf("#"))) : console.log(login_id) ;
Running example
function username(login_id) {
return login_id.includes('#') ? login_id.substring(0,login_id.lastIndexOf("#")) : login_id ;
}
console.log(username("sa-testaccount0125#abc.com")) ;
console.log(username("sa-testaccount0125")) ;
Code
if(x.substr(0,4)=='init') {
output += 'Initialised<br>';
var rgx = /^\[typ-$\]/i;
if (rgx.test(x))output+='Type given<br>';
else output+='No type: '+x+'<br>';
}
container.append(output);
What I'm trying to do
I'm simulating a command-line terminal for a website. One command is init which carries the parameter type. The parameter is set by typing:
init [typ-Foo]
I'm trying to then get the value of the type parameter (in this case, Foo).
What's happening
I'm failing to get the value at all. It's returning No Type: init [typ-Foo] which is what the function returns when no value is found. I haven't played about with Regex before so I'm sure that my command is incorrect but I'm unable to make it work!
var result = /\[typ-([^\]]+)]/.exec( userInput );
if (result){
console.log("type: " + result[1]);
}
else {
// no type
}
If result is null, then there's no type. If it isn't, the type is in result[1]
This regex looks a little complicated because we're using [ and ]s in their special, regex meaning and also as literal characters.
Try something more like this:
var rgx = /^init \[typ-(.*)\]$/i;
m = x.match(rgx);
if ( m != null ) {
output += 'Initialised<br>';
output+='Type given<br>';
output+='Argument: ' + m[1]; // note this is the "Foo" value
}
else {
output+='No type: '+x+'<br>';
}
container.append(output);
This pattern should do the trick.
var rgx = /^init\s\[typ\-([^\]]+)\]/;
This is what happens.
From Regexper.com