Match returning 100 instead of actual value - javascript

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;
}
}

Related

Function can accept character input and the number of loop

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.

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.

Regext to match any substring longer than 2 characters

regex-pattern-to-match-any-substring-matching exact characters longer-than-two-characters-from-a-provided input,where ever exact string matches
Only pot or potato should be highlighted, instead of ota or ot, when user type pota and click search button.
Please find code below where matched string is highlighted.
// Core function
function buildRegexFor(find) {
var regexStr = find.substr(0,3);
for (var i = 1; i < find.length - 2; i++) {
regexStr = '(' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
}
return regexStr;
}
// Handle button click event
document.querySelector('button').onclick = function () {
// (1) read input
var find = document.querySelector('input').value;
var str = document.querySelector('textarea').value;
// (2) build regular expression using above function
var regexStr = buildRegexFor(find);
// (3) apply regular expression to text and highlight all found instances
str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>");
// (4) output
document.querySelector('span').textContent = regexStr;
document.querySelector('div').innerHTML = str;
};
consider "meter & parameter" as one string, if type meter in input box and click search button. meter should be highlighted as well as meter in parameter should highlight.Thanks in advance
Your for loop is set to go from i = 1, while i is less than find.length-2. find.length is 4. 4-2 is 2. So your for loop is set to go from i = 1 while i is less than 2. In other words, it's operating exactly once. I have no idea what you thought that for loop was going to do, but I'm betting that isn't it.
Prior to the for loop, regextr is set equal to the string pot (the first three characters of the find string. The first (and only) time through the for loop, it is set to a new value: the left paren, the existing value (pot), the fourth character of find (a), the question mark, the vertical bar, and three characters from find starting with the second. Put those together, and your regextr comes out to:
(pota?|ota)
That RegEx says to find either the string "pota" (with the a being optional, so "pot" also works) or the string "ota". So any instances of pota, pot, or ota will be found and highlighted.
If you just wanted "pota?", just eliminate the right half of that line inside the for loop. Better yet, replace the entire subroutine with just a line that appends the ? character to the find string.

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)

indexOf returns -1 for the first letter of a word

I'm trying to make a simple hangman game.
I logged the word to the console what should be guessed (this will be removed when the game is finished.)
Now I'm trying to make the player guess if the letter is in the word, if it is, it should reveal itself.
But my problem here is: I use the indexOf().
The first letter of the word is -1 instead of 0,
also the letters that are not in the word are -1.
So I can't really check if it's an available letter or not since the first letter always returns -1. I added a screenshot to make it a little bit more clear.
notice how 'H' is the first letter of the word: Hond.
And how the alertbox says it's at the index of -1.
This is the function I used:
function guessLetter(letter){
var letterVal = letter.value;
alert(rand.indexOf(letterVal));
}
rand is the variable used for storing a random word.
The first letter of the word is -1 instead of 0
No. The first letter of the word is denoted by the index 0. If indexOf does not find the letter h in the string Hond, that has a different reason: it uses a case-sensitive comparison. Yielding -1 for that case it the correct result.
For a case-insensitive search, just make sure all letters have the same casing:
alert(rand.toLowerCase().indexOf(letterVal.toLowerCase()) > -1
? "It's there"
: "It's not there");
To reveal the letters that were guessed, indexOf doesn't seem to be the correct tool anyway. Better use something along the lines of
var rand = "Hond";
var guesses = [];
for ( /* every guess */ ) {
guesses.push(guess.toLowerCase());
var revealed = "";
for (var i=0; i<rand.length; i++)
if (guesses.indexOf(rand[i].toLowerCase() > -1)
revealed += rand[i];
else
revealed += "_";
}
show(revealed);
}
if your search is case sensitive, there is no 'h' in 'Hond'. what does clicking 'o' show? it should show 1.
try converting the word to upper or lower case then compare.

Categories

Resources