Home > Net >  When match function doesn't match
When match function doesn't match

Time:09-17

var x = 'CHQ10';
var y = (x.match(/\d /)[0]);//10

When match can identify digit, i got the result. But in case there is no digit, i got an error

TypeError: Cannot read properties of null (reading '0')

var x = 'CHQ';    
var y = (x.match(/\d /)[0]===0)?0:(x.match(/\d /)[0]);

I've try with null and undefined but cannot be accepted

CodePudding user response:

The match function documentation can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

There you will find this:

Return value An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

The error that you are receiving is:

TypeError: Cannot read properties of null (reading '0')

That means that you are trying to access the index 0 of something that is not an array, null in this case

Here is an example:

    const input_text_that_matches_the_regular_expression = 'CHQ10';
    const input_text_that_does_not_matches_the_regular_expression = 'CHQ';
    const regular_expression = /\d /
    
    /**
 * If we compare input_text_that_matches_the_regular_expression with the regular expression
 * the 10 will match, and according to the match documentation, we will get an array
 **/
const match = input_text_that_matches_the_regular_expression.match(
  regular_expression,
); // [10] - array of matches, so we can access match[0] to get the first match, which is 10

/**
 * If we compare input_text_that_does_not_matches_the_regular_expression with the regular expression
 * the 10 will not match, and according to the match documentation, we will get null
 */
const match =
  input_text_that_does_not_matches_the_regular_expression.match(
    regular_expression,
); // null  - no matches, if we try to access match[0] we will get an error

How to prevent this error?

We have 2 main options, the first one ( more readable )

  /**
 * Check with an if statement if the match is null or not
 */
if (match) {
  // do something
} // here you could also add an else statement if needed, this else would mind that there is no match found

The second option, as mentioned by CherryDT, is to use a coalesce operator

/**
 * You can also use the optional chaining and coalesce operator to get the first match, if there is no match, it will return null
 */
const first_match = match?.[0] ?? null;

If you don't know anything about coalesce operator or optional chaining, information can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

and if you need more information about the error itself, this page may help =) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  • Related