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)
Related
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.
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.
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;
}
}
Say I have an array of strings of the following format:
"array[5] = 10"
What would be the best solution to parse it in JavaScript?
Ashamedly not being familiar with regular expressions, I can come up only with something like this:
for (i in lines){
var index = lines[i].indexOf("array[");
if (index >= 0) {
var pair = str.substring(index + 6).trim().split('=');
var index = pair[0].trim().substring(0, pair[0].trim().length - 1);
var value = pair[1].trim();
}
}
Is there a more elegant way to parse something like this? If the answer is using regex, would it make the code slower?
Don't ask which approach is faster; measure it!
This is a regular expression that should match what you've implemented in your code:
/array\[(\d+)]\s*=\s*(.+)/
To help you learn regular expression, you can use a tool like Regexper to visualize the code. Here's a visualization of the above expression:
Note how for the index I assumed it should be an integer, but for the value any characters are accepted. Your code doesn't specify that either the index or value should be numbers, but I made some assumptions to that effect. I leave it as an exercise to the reader to tweak the expression to something more fitting if need be.
If you want a regular expression approach, then, something like so will do the trick: ^".*?\[(\d+)\]\s*=\s*(\d+)"$. This will match and extract the number you have in your square brackets (\[(\d+)\]) and also any numbers you will have at the end just before the " sign.
Once matched, it will put them into a group which you can then eventually access. Please check this previous SO post to see how you can access said groups.
I can't comment on speed, but usually regular expressions make string processing code more compact, the drawback of which is that the code is usually more difficult to read (depending on the complexity of the expression).
Regex is slower than working by finding the index of a given char, regardless of the language.
In your case, don't use split but only substring at given index.
Moreover, some hints to improve perf : pair[0].trim() is called twice and first trim is useless because you already call pair[1].trim().
It's all about algorithms…
Here is a faster implementation :
for (var i = 0; i < lines.length; i++) {
var i1 = lines[i].indexOf("[");
var i2 = lines[i].indexOf("]");
var i3 = lines[i].indexOf("=");
if (i1 >= 0) {
var index = lines[i].substring(i1, i2);
var value = lines[i].substring(i3, lines[i].length-1).trim();
}
}
If all you want to do is extract the index and value, you don't need to parse the string (which infers tokenising and processing). Just find the bits you want and extract them.
If your strings are always like "array[5] = 10" and the values are always integers, then:
var nums = s.match(/\d+/);
var index = nums[0];
var value = nums[1];
should do the trick. If there is a chance that there will be no matches, then you might want:
var index = nums && nums[0];
var value = nums && nums[1];
and deal with cases where index or value are null to avoid errors.
If you genuinely want to parse the string, there's a bit more work to do.
I'm trying to do the same thing that this guy is doing, only he's doing it in Ruby and I'm trying to do it via Javascript:
Split a string into an array based on runs of contiguous characters
It's basically just splitting a single string of characters into an array of contiguous characters - so for example:
Given input string of
'aaaabbbbczzxxxhhnnppp'
would become an array of
['aaaa', 'bbbb', 'c', 'zz', 'xxx', 'hh', 'nn', 'ppp']
The closest I've gotten is:
var matches = 'aaaabbbbczzxxxhhnnppp'.split(/((.)\2*)/g);
for (var i = 1; i+3 <= matches.length; i += 3) {
alert(matches[i]);
}
Which actually does kinda/sorta work... but not really.. I'm obviously splitting too much or else I wouldn't have to eliminate bogus entries with the +3 index manipulation.
How can I get a clean array with only what I want in it?
Thanks-
Your regex is fine, you're just using the wrong function. Use String.match, not String.split:
var matches = 'aaaabbbbczzxxxhhnnppp'.match(/((.)\2*)/g);