How to detect that a regex that matches and capture has not found a match

Viewed 35

I have the following javascript code that uses regex to match if a certain string contains a phone number in international fomart and capture the number

var myString1 = "some other string +123456789 some other string";
var myString2 = "some other string 123456789 some other string";

var regex = new RegExp("\\+(\\d+)");
var number = myString1.match(regex)[1];

if (typeof (number) == "string") {
  // some positive actions
}
else {
  // some negative actions
}

The code works perfectly if there is a match and for the code above, the if statement will return true so some positive actions will be executed

The problem is that if the match is not found (e.g when myString2 is used), the if statement will neither return true nor false meanig some negative actions also won't be executed

i have tried

if (number == "" || number == null) {
  // some negative actions
}
else {
  // some positive actions
}

The else part will work if there is a match but if there is not match it wont detect if there is no match. i have tried printing the datatype of number using typeof(number) when mystring2 is used and it also returns nothing. it is not null or empty

What condition can i use to detect if there is no match

NB: I must use regex

1 Answers

It's not working because you are getting the second item in the array immediately after calling match(). If there is no match, it returns null, and thus you get an error.

Instead, first check whether the match() method returns an array (either with Array.isArray() or simply a null check), then get the second item:

var myString1 = "some other string +123456789 some other string";
var myString2 = "some other string 123456789 some other string";

var regex = new RegExp("\\+(\\d+)");
var number = myString2.match(regex);

if (Array.isArray(number)) {
  number = number[1];
  console.log('positive');
} else {
  console.log('negative');
}

Related