Weird regex problem in CS

Maybe I’m doing something wrong here but the following regex just will not validate as true - despite this being perfectly valid …

let my_string = “012345”; // included here for the avoidance of doubt - but it actually comes from a fragment_presenter.get_value() call

let regex = new RegExp(“^\d{6}$”);

cs.log(“Test Result: “ + regex.test(my_string));

please excuse any minor code transcription issues

It’s supposed to return true if my_string is exactly 6 characters in length. Works fine in every regex validator I can find but not in CS. Always comes back false.

Before anyone asks - yes my actual string is tested as being 6 digits long :grin:

This specifically is a fragment validator component.

Thoughts ?

Try:

let regex = new RegExp(/^\d{6}$/);

or

let regex = /^\d{6}$/;

More specifically:

main: function(fragment_presenter) {

    // const regEx = /^\d{6}$/;

    const regEx = new RegExp(/^\d{6}$/);

     // cs.log(regEx.test(fragment_presenter.get_value()));

    if (!regEx.test(fragment_presenter.get_value())) {

        return {

            valid: false,

            error: "Value must be 6 digits long."

        }

    }

    return true;

}

will check it out thanks.

Did you get this working?

To clarfy, I think the issue is your string is not properly escaped…

let regex = new RegExp("^\d{6}$");

would need to be

let regex = new RegExp("^\\d{6}$");

or, as Neil pointed out you can use slash notation instead of double quotes to avoid this…

let regex = new RegExp(/^\d{6}$/);

Note, this is a native JS syntax thing, not specific to Code Studio.