Function can accept character input and the number of loop - javascript

i have some question about logic,but i stuck in this question. i dont understand what this question means
Write a function with the following conditions:
Function can accept character input and the number of loop
Each of the first characters will be taken out from the string and input into a new string
Then every the number of inputs loop take out from the string and input into a new string
Do this until the characters in the string empty
Return the New Of String
Example:
function solution(string, numberOfLoop)
solution("MISTERALADIN",4) Output: MEAIANLTSRID
function Solution(string, numberOfLoop) {
let newString = string[0];
for (let i = 0; i < numberOfLoop; i++) {
string = string.subs
for (let j = 0; j < string.length; j++) {
newString += string[j];
}
}
}
// function Solution (string, numberOfLoop) {
// // console.log(string)
// let newString = string[0]
// }
console.log(Solution("MISTERALADIN", 4));

The problem is very poorly written, apparently by someone who doesn't speak English well (unless you did the translation, then maybe you didn't translate it well).
The parameter "number of loop" doesn't really describe it well. It's not the number of iterations to perform, so you don't use it as the limit in a for loop.
Based on the example, it's the steps between characters to select. So it's the increment that you should add to to the iteration variable in the loop. The limit is the length of the string.
So what you're supposed to do is:
Copy the characters at indexes 0, numberOfLoop, 2*numberOfLoop, 3*numberOfLoop, etc. to the result, and remove them from the input string.
Repeat the above step until the input string is empty.
I'm not writing the solution for you. You asked what the question means, solving it is still your problem.
It will probably be easier to do this by first converting the string to an array (you can do this with the split() method), then you can use splice() to remove elements from it.

Related

Convert char to String in Javascript

Read it, Before it gets marked as duplicate
Sorry! I couldn't come up with a better description of the question
Anyways, I was making a simple program which reverses the given word (e.g 'word' to 'drow'). I was trying to convert the String into char array first and then printing each character backwards in the console using for loop. However, I need to save the value in a String now that I can't seem to figure out.
This is the code here:
var answer = document.getElementById("ta").value;
var arr = answer.split("");
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str = arr[i];
console.log(str); //it works but displays each character individually
}
I just want all the characters in a String. Please help! Brevity in the answer would be appreciated
JavaScript unlike other oops, provide an inherited reverse function that reverses array. So one answer to this whould be:
let arr = answer.split("") //note this creates an array with each char as element of array
arr = arr.reverse(); //this reverses the array
let string = arr.join(""); //this joins the array into a single string
Another method would be the one you are trying to do, create your own reverse function. You are doing it all right but just missing a step, that is to join the array, you are simply printing each letter of the array and thats the property of console.log that each console.log prints to a new line. That explains why you are getting it all in new line.
var answer = document.getElementById("ta").value;
var arr = answer.split("");
var str ="";
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str =str + arr[i];
}
console.log(str); //it should be outside the loop and print string once it has been formed
P.S:I have given as much detail I can on this to get you started but this is a very basic question and doesnt deserve to be here, you should follow some basic concepts of js on mdn or w3schools. Plus google your problems before turning to stackoverflow.
If you want to put all the characters in str you can try this way:
str= str+arr[i]
or try this way:
var str = "";
arr.forEach(element => {str= str+element});
console.log(str)

JS - Iterate through text snippet character by character, skipping certain characters

I am using JS to loop through a given text, refered to in below pseudo as "input_a".
Based on the contents of another, and seperate text "input_b" I would like to manipulate the individual characters of text "input_a" by assigning them with a boolean value.
So far I've approached it the following way:
for (i=0; i < input_a.length; i++) {
if (input_b[i] == 0){
//do something to output
}
}
Now the issue with this is that the above loop, being that it uses .length also includes all blank/special characters whereas I would only like to include A-Z - ommitting all special characters (which in this case would not be applicable to recieve the boolean assigned to them).
How could I approach this efficiently and elegantly - and hopefully without reinventing the wheel or creating my own alphabet array?
Edit 1: Forgot to mention that the position of the special characters needs to be retained when the manipulated input_a is finally delivered as output. This makes an initial removal of all special characters from input_a a non viable option.
It sounds like you want input_a to retain only alphabetical characters - you can transform it easily with a regular expression. Match all non-alphabetical characters, and replace them with the empty string:
const input_a = 'foo_%%bar*&#baz';
const sanitizedInputA = input_a.replace(/[^a-z]+/gi, '');
console.log(sanitizedInputA);
// iterate through sanitizedInputA
If you want the do the same to happen with input_b before processing it, just use the same .replace that was used on a.
If you need the respective indicies to stay the same, then you can do a similar regular expression test while iterating - if the character being iterated over isn't alphabetical, just continue:
const input_a = 'foo_%%bar*&#baz';
for (let i = 0; i < input_a.length; i++) {
if (!/[a-z]/i.test(input_a[i])) continue;
console.log(input_a[i]);
}
You can check if the character at the current position is a letter, something like:
for (i=0; i < input_a.length; i++) {
if(/[a-z]/i.test(input_a[i])){
if (input_b[i] == 0){
//do something to output
}
}
}
the /[a-z]/i regex matches both upper and lower case letters.
Edited as per Edit 1 of PO
If you would like to do this without RegEx you can use this function:
function isSpecial(char) {
if(char.toLowerCase() != char.toUpperCase() || char.toLowerCase.trim() === ''){
return true;
}
return false;
}
You can then call this function for each character as it comes into the loop.

Variables incorporating dynamic numbers

I'm trying to make hangman for a Grade 12 Assessment piece.
I need to create variables due to the length of the current word chosen to be guessed. For example, if the word is 'cat', then
letter0 = 'c'
letter1 = 'a'
letter2 = 't'
So far, I have gotten some progress with a for loop.
for (i = 0; i <= currentWord.length){
//var letter(i) = currentWord.charAt(i)
i++
}
The commented out line was what I was aiming for, where the letter position would be put into the variable. Obviously this doesn't work, as the variable is just straight up read as letter(i) instead of letter(possible number). The loop would then stop once the length had been reached, and therefore there would be a unique variable for each letter of currentWord.
Any ideas of how to make this work?
Thanks!
if you want to convert string to character array use currentWord.split("")
it return array containing each character as element.
If looping is your goal, you don't even need to split, this works as expected:
const word = "cat";
for (let i = 0; i < word.length; i++) {
console.log(word[i]); // Will output "c" then "a" then "t"
}
In most programming languages, strings are just arrays of letters anyway.
If you really want an array (there are things you can do to arrays and not to strings), you can use word.split("") which returns an array of letters.
I'd suggest to split your word into an array, like Hacketo suggested:
var letters_array = "cat".split('');
Then you can loop over that array (check out the answers for Loop through an array in JavaScript)

Match returning 100 instead of actual value

I have an array that I'm cycling through. For each value in the array, I'm analyzing it and then shunting the value off into another array based on which conditions it meets. For the purpose of this question, though, I'm simply trying to count how many periods are in the current array item.
Here's the relevant part of the code I'm trying to use:
for(i = 0; i < (sortarray.length) -1; i++)
{
var count = (sortarray[i].match(/./g)||[]).length;
console.log(count + ' periods found in name' + sortarray[i]);
if (count > 1)
{
alert('Error: One or more filenames contain periods.');
return;
}
else ...
Most values are filenames and would have a single period, whereas folder names would have no periods. Anything with more than 1 period should pop up an alert box. Seems simple enough, but for some reason my variable keeps returning 100 instead of 1, and therefore the box always pops up.
Is there a better way to count the dots in each array value?
The problem is with your regexp. The dot (.) means any char. Furthermore (since you are using g option) your regex will match the whole string.
That's why you're getting 100: length is being called on your full string.
Thus you should escape dot so that it will really look for dots instead of any char.
sortarray[i].match(/\./g)
Instead of that logic you can just compare the first index of . and last index of ., if they are not equal that means the filename has more then one .
for(i = 0; i < (sortarray.length) -1; i++)
{
if (sortarray[i].indexOf(".")!=sortarray[i].lastIndexOf("."))
{
alert('Error: One or more filenames contain periods.');
return;
}
}

Converting strings into a series of underscores based on length in JavaScript

So, as a relatively new programmer, I'm trying to create a very simple ASCII hangman game. I'm trying to figure out how to create a string of underscore's(_) based on the length of the word chosen.
For example, take the word Kaiser, I'd like to take, 'word.length(where word = "Kaiser")and convert it to "_ _ _ _ _ _`". Thanks in advance!
My first guess is something like this would work.
var underscored = string.split('').map(function(char) {
return char = '_ ';
}).join('');
Get every character in the string with the split function, and change the state of every character, using the map function. However, this will just give us an array. We need to perform type conversion again to turn it back to a string. To do this, we can use the join method. The delimiter we join is simply an empty string ''.
Another possibility is with the replace function
var underscored = string.replace(/./g, '_ ');
The regular expression here is very simple. The period . indicates any character. The global(g) flag means find all instances of the previous regex.
The second parameter of this function is what we want these characters to become. Since we want a space between underscores, this will be _.
Note that the replace method is not destructive. In other words, it does not modify the original array. You would need to store this in a separate variable. Because if you call string again, kaiser will be returned.
var str = "Kaiser";
var resStr = "";
for (i = 0; i < str.length; i++) {
resStr = resStr + " _";
}
You don't have to replace anything just create new string based on length of the first word, example :
var underscore_word = Array(word.length).join("_ ");
Take a look at Repeat Character N Times.
Hope this helps.

Categories

Resources