Beginner, reg & if...else questions 2 in 1

Hi,
I’m just working my way through some beginner challenges but I’ve hit some stumbling blocks. Please help :slight_smile:

  1. I want to check for 2 to 4 recurrences of a character in a string using regex.
    When not a function the code seems to work. How do I make my 2nd argument my regex search term?
    I tried it on its own ‘a’ , “a” as a string and as regex /a/.

function check (string, a) {

let regex = /a{2,4}/g  

return string.match(regex));
}

console.log(check(“hello”, /l/));

  1. problem…

function ascending(array){

let ascendingNum = ""
for (let i = 0; i < array.length; i++){
    console.log(array[i], array[i-1]); 
    if (array[i] > array[i-1]){
        ascendingNum += array[i];

     } else {break;}
         
    }
return ascendingNum;    

}

console.log(ascending([1,2,3,4,5]));

when i do this “console.log(array[i], array[i-1])” without the if statement, it gives me the value i’d expect. However, when i put the if statement in console.log doesn’t produce anything anymore and it just produces ‘1 undefined’

I’d ideally like it to produce the array until the numbers are not ascending anymore, in which case, break the loop.

  • Also, just another question. If my argument is an array, do I have to write my parameter as an array in [array] like this, or can it not be in the brackets?

Thanks for your help!

Hey, happy to see you here :slight_smile:

  1. Using variables to construct regex dynamically is actually a bit of a complex topic. Here’s a stackoverflow thread about it, if you want to try. But you can usually do the same thing as the regex through string manipulation.

  2. Here the issue is actually accessing out of bounds index. Look at your for loop, and ask yourself what i is on the first iteration. It’s 0, now put that into array[i-1] you get array[-1]. So you see the issue is you are trying to look at an array element that does not exist, hence the reason for undefined in your console. This is easily fixed by setting i=1 on the for loop initialization.

Thank you :slight_smile:
Number 2! of course!! you know, i think i even did a similar problem where i had to do the same thing a little earlier on. Thank you.

Ooo ok, thats good to know for problem 1. Do you mind sharing the sackover flow link, sorry i dont think it has come through… im sure it will probably be over my head.

Thanks again!

Hey sorry I just forgot to paste the link haha

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.