Reply To: Isaac Harned – Here for forms with javascript

  • Liz Larsen

    Member
    October 31, 2022 at 6:41 pm
    Points: 5,232
    Rank: UC2 Brainery Purple Belt UC2 Brainery Purple Belt Rank

    @isaac-harned

    Also the line:

    let childMask = new RegExp(“^” + tap + “-[\\d]{1,2}$”);

    when I plug this into regex101, I get some weird search parameters. Never worked with the RegEx constructor, so please bear with me here =)

    So if the previous tap variable only stores the number at the end of the string (Let’s say NumberOfTaps1), then this would be constructed as such:

    /^1-[\\d]{1,2}$/

    The part that is tripping me up is the double slashes I think, what does this do to the digit search?

    You can’t plug that particular regular expression into regex101. That website is meant for only regular expressions, not for any other code (ie JavaScript).

    The new RegExp(“string”) is JavaScript, therefore regex101 doesn’t know what to do with it.

    new RegExp(“string”) allows you to take a string and let JavaScript know to turn it into a regular expression. Just like any other string, we can add variables.

    var name = "Liz";
    console.println("Hello, my name is " + name + ".");

    The code above will print “Hello, my name is Liz.” to the console. This is basically what we’re doing, except with a regular expression as the end result.

    To answer your original question, we use the double slashes because new RegExp is a string and the \ is an escape character in JavaScript. To escape an escape character, we have to add an additional \. The first \ is the escape character, letting JavaScript know that the second \ is to be interpreted as a string character.

    To test that this code works, I went to codepen.io. You can see in the attached photo how heavily I have to edit the global code to test the functionality. But it was enough proof of concept for me to know that the tap variable in my childMask regular expression was working.

    I hope that makes sense.