DOMException while copying text to clipboard in javascript - 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.

Related

Uncompress a String, repeat chars `n` times

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('');
};

Extracting certain substring from a string

I want to extract the last part of this string : "https://steamcommunity.com/profiles/76561198364464404".Just the numbers after '/profiles'.But the problem is the URL can change sometimes.
There are two types of url
1.First one is "https://steamcommunity.com/profiles/76561198364464404" with "/profiles" and then the "id"(id is the numbers after '/profiles').
2."https://steamcommunity.com/id/purotexnuk".Second is this type.Where "/profiles" doesn't exist.
I have come up this code :
let inc;
const index = 27;
const string = 'https://steamcommunity.com/id/purotexnuk';
if (string.includes('profiles')) {
inc = 9;
} else {
inc = 3;
}
console.log(string.slice(index + inc, -1));
The above code checks wheather the string "/profiles" is present.If the string contains "/profiles".inc will be 9.So that slice starts from the right side of the string(url) and ends at the first '/' from the right.inc is 9 becuase "profiles/" length is 9.Similar way if the string(url) contains "id".The slice will start from the end and stop at the first '/' from the right.inc will be 3 becuase "id/" length is 3.
The index is always constant because ,"/profiles" or "/id" only occurs after "https://steamcommunity.com" whose length is 27.Is there any better way i can extract only the profile id or profile name?
(profile id - 76561198364464404)
(profile name - purotexnuk )
You can use regex for this, it will also take care if your url ends with / or has query parameters example https://steamcommunity.com/id/purotexnuk?ref=abc
/.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i
example:
const regex = /.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i;
const matches = regex.exec('https://steamcommunity.com/id/purotexnuk');
console.log(matches[1]);
You can split the string with delimiter / and return the last value value from the array;
function getNum(str) {
const arr = str.split('/');
if (!isNaN(arr[arr.length - 1])) {
return arr[arr.length - 1];
}
return ' no number ';
}
const st1 = "https://steamcommunity.com/profiles/76561198364464404";
const st2 = "https://steamcommunity.com/profiles/76561198364464404";
const st3 = "https://steamcommunity.com/id/purotexnuk";
console.log(getNum(st1));
console.log(getNum(st2));
console.log(getNum(st3));
Or do it in one line:
const string = 'https://steamcommunity.com/id/purotexnuk';
console.log(string.slice(string.lastIndexOf("/") + 1, string.length));

Filtering ranges of letters in Javascript

I have to create a program that takes the first letter of a prompt, and if that letter is between a and k, then it has to produce a certain output, if it's between l and p another and so on. Is there a way to do this without writing every letter of the alphabet down? (sorry I'm a new coder)
I think you should try to solve the problem, before asking - so you can show what you've already tried.
I think the snippet below points you in the right direction - but it takes any character, not just letters. You need to get everything filtered out that's not a lower case letter.
// UI elements
const input = document.getElementById('input1')
const result = document.getElementById('result')
// input event
// only the first character is taken into account
input.addEventListener('input', function(e) {
// adding the characters of the input value to an array, and
// picking the 0th element (or '', if there's no 0th element)
const a = [...this.value][0] || ''
let ret = ''
if (a !== '') {
// lowercaseing letters, so it's easier to categorize them
ret = categorizeAlphabet(a.toLowerCase().charCodeAt(0))
} else {
ret = 'The input is empty'
}
// displaying the result
result.textContent = ret
})
// you could use this function to filter and categorize
// according to the problem ahead of you - and return the result
// to be displayed.
// In this example this function is rather simple, but
// you can build a more complex return value.
const categorizeAlphabet = (chCode) => {
return `This is the character code: ${chCode}`
}
<label>
First character counts:
<input type="text" id='input1'>
</label>
<h3 id="result">The input is empty</h3>

Function behaves strangely after first onclick

I have the following HTML:
<input type = "text" id = "pick"> <input type = "submit" value = "Submit" onclick = "guessWord()">
That runs my js function which works fine (with unrelated hiccups) on the first call. But if I change my text and submit it again without reloading my initial if/else statement behaves incorrectly. Specifically, the if/else is supposed to check if the user inputted word is in an array. It works properly on the first call, but after that it jumps to the else block even when it shouldn't.
Here is the js (apologies in advance for including the whole function, I'm just usually asked to include more code than I initially do):
function guessWord() {
var comWords, match, compWord = "";
var possWords = dictFive;
var firstFive = ["vibex", "fjord", "nymph", "waltz", "gucks"]; // note: right now choosing any of these words results in unexpected behavior -- either it doesn't accept them or it freezes.
var inputWord = document.getElementById("pick").value.toLowerCase().replace(/\s+/g, '');
if (possWords.includes(inputWord)) { // checks to see if the user inputted word is in our dictionary.i f not, requests a different word.
// start game loop:
// in order to try and get as much information as possible in the first few turns I start by guessing the five words in firstFive[]: vibex, fjord, nymph, waltz, gucks. together, these words give us information about 25 letters.
for (let d = 0; d < inputWord.length; d++) { // this loop will run for the length of the inputted word, making it scaleable so in the future the program could accept shorter or longer words. within the current scope it will always be 5.
compWord = firstFive[d]; // the computers word will loop through each word in firstFive[].
if (inputWord === compWord) { // if the word matches the user inputted word:
document.getElementById("otpt").innerHTML = "Your word was: " + firstFive[d] + ". I guessed it in " + (d + 1) + " turns.";
return;
} else { // if the word is not the user inputted word, then:
comWords = (inputWord + compWord).split('').sort().join(''); // we combine the users word with the comps word and sort them by character.
match = comWords.length - comWords.replace(/(\w)\1+/g, '$1').length; // match produces a numerical value for how many letters matched between both words.
for (let e = 0; e < possWords.length; e++) { // loop to cycle through our dictionary.
for (let f = 0; f < inputWord.length; f++) { // loop to cycle through all the different match options.
if (match === 0) { // if there are no matches we can:
if (possWords[e].includes(firstFive[f])) { // go through the dict and get rid of every word that has letters in common with the word.
possWords.splice(e, 1);
}
} else if (match === f) { // if there's at least one letter in common:
comWords = (possWords[e] + compWord).split('').sort().join(''); // as we cycle through the dict, pick each available word, combine and sort with the chosen word,
var matchFive = comWords.length - comWords.replace(/(\w)\1+/g, '$1').length; // and then find how many letters match.
if (matchFive != match) { // any words in dict that have a different match value can be deleted.
possWords.splice(e, 1);
}
}
}
}
}
}
// once we've worked through the words in firstFive[] we start guessing randomly.
for (let a = 0; a < possWords.length; a++) { // the loop max is set to the length of the array because that's the maximum amount of time the guessing can take.
compWord = possWords[Math.floor(Math.random() * possWords.length)]; // choose a random word.
if (compWord === inputWord) { // check if the random word is the inputted word. if it is:
document.getElementById("otpt").innerHTML = "Your word was: " + compWord + ". I guessed it in " + (a + 5) + " turns. I had " + possWords.length + " remaining words that were possible matches.";
return;
} else { // while the word still isn't correct:
comWords = (compWord + inputWord).split('').sort().join(''); // again, we join and sort it.
match = comWords.length - comWords.replace(/(\w)\1+/g, '$1'); // find its match value.
for (let c = 0; c < inputWord.length; c++) { // loop through inputted word's length to check all letters.
if (match === 0) { // again, no matches we can safely delete all words with those letters.
if (possWords.includes(compWord[c])) {
possWords.splice(c, 1);
}
} else if (match === c) { // if match is higher than 0:
for (let g = 0; g < possWords.length; g++) {
comWords = (possWords[g]+ compWord).split('').sort().join('');
matchAll = comWords.length - comWords.replace(/(\w)\1+/g, '$1');
if (match != matchAll) {
possWords.splice(g, 1);
}
}
}
}
}
}
} else { // If the user inputted word was not in our dictionary, requests a different word:
document.getElementById("otpt").innerHTML = "Please choose a different word.";
}
}
(For context, dictFive is an array located on a separate file.) The code is trying to guess the user inputted word by checking how many letters match and then splicing out words from the master array if they can't match, so the array possWords starts with about 2500 words and gets narrowed down to a few hundred by the end of the function. As far as I can tell, the function should be resetting the vars properly every time it's called, though, but I'm guessing it isn't for some reason?
Your dictFive array is being spliced each time the function is called.
When you set possWords = dictFive, and then splice possWords later, you're also splicing dictFive because both variables refer to the same array. Then, the second time the function is run, dictFive is still in its spliced state. Instead of setting possWords = dictFive, try making a copy of the array. That way, you'll splice the copy without affecting the original, dictFive. You can clone an array by possWords = dictFive.slice().
var dictFive = [0,1,2,3,4]; // Just an example of whatever dictFive might be
var possWords = dictFive; // This makes possWords refer to the same thing as dictFive
possWords.splice(0, 1); // Splicing the array at whatever point
possWords // [1,2,3,4] because the 0th element was spliced out
dictFive // also [1,2,3,4] because both dictFive and possWords are the same array
compare that to
var dictFive = [0,1,2,3,4];
var possWords = dictFive.slice(); // This makes a copy of the array instead of referencing the original dictFive
possWords.splice(0, 1);
possWords // [1,2,3,4];
dictFive // Now, this array is still [0,1,2,3,4] because only the possWords array was spliced. dictFive wasn't affected.

Look for substring in a string with at most one different character-javascript

I am new in programing and right now I am working on one program. Program need to find the substring in a string and return the index where the chain starts to be the same. I know that for that I can use "indexOf". Is not so easy. I want to find out substrings with at moste one different char.
I was thinking about regular expresion... but not really know how to use it because I need to use regular expresion for every element of the string. Here some code wich propably will clarify what I want to do:
var A= "abbab";
var B= "ba";
var tb=[];
console.log(A.indexOf(B));
for (var i=0;i<B.length; i++){
var D=B.replace(B[i],"[a-z]");
tb.push(A.indexOf(D));
}
console.log(tb);
I know that the substring B and string A are the lowercase letters. Will be nice to get any advice how to make it using regular expresions. Thx
Simple Input:
A B
1) abbab ba
2) hello world
3) banana nan
Expected Output:
1) 1 2
2) No Match!
3) 0 2
While probably theoretically possible, I think it would very complicated to try this kind of search while attempting to incorporate all possible search query options in one long complex regular expression. I think a better approach is to use JavaScript to dynamically create various simpler options and then search with each separately.
The following code sequentially replaces each character in the initial query string with a regular expression wild card (i.e. a period, '.') and then searches the target string with that. For example, if the initial query string is 'nan', it will search with '.an', 'n.n' and 'na.'. It will only add the position of the hit to the list of hits if that position has not already been hit on a previous search. i.e. It ensures that the list of hits contains only unique values, even if multiple query variations found a hit at the same location. (This could be implemented even better with ES6 sets, but I couldn't get the Stack Overflow code snippet tool to cooperate with me while trying to use a set, even with the Babel option checked.) Finally, it sorts the hits in ascending order.
Update: The search algorithm has been updated/corrected. Originally, some hits were missed because the exec search for any query variation would only iterate as per the JavaScript default, i.e. after finding a match, it would start the next search at the next character after the end of the previous match, e.g. it would find 'aa' in 'aaaa' at positions 0 and 2. Now it starts the next search at the next character after the start of the previous match, e.g. it now finds 'aa' in 'aaaa' at positions 0, 1 and 2.
const findAllowingOneMismatch = (target, query) => {
const numLetters = query.length;
const queryVariations = [];
for (let variationNum = 0; variationNum < numLetters; variationNum += 1) {
queryVariations.push(query.slice(0, variationNum) + "." + query.slice(variationNum + 1));
};
let hits = [];
queryVariations.forEach(queryVariation => {
const re = new RegExp(queryVariation, "g");
let myArray;
while ((searchResult = re.exec(target)) !== null) {
re.lastIndex = searchResult.index + 1;
const hit = searchResult.index;
// console.log('found a hit with ' + queryVariation + ' at position ' + hit);
if (hits.indexOf(hit) === -1) {
hits.push(searchResult.index);
}
}
});
hits = hits.sort((a,b)=>(a-b));
console.log('Found "' + query + '" in "' + target + '" at positions:', JSON.stringify(hits));
};
[
['abbab', 'ba'],
['hello', 'world'],
['banana', 'nan'],
['abcde abcxe abxxe xbcde', 'abcd'],
['--xx-xxx--x----x-x-xxx--x--x-x-xx-', '----']
].forEach(pair => {findAllowingOneMismatch(pair[0], pair[1])});

Categories

Resources