grasshopper
grasshopper

Reputation: 113

String return statement JS

I'm working on a JS exercise and it semi works but it's not returning a statement when the last conditional is satisfied, only an empty set of parenthesis. I'm not too sure why but any help is appreciated!

function isItANum(str) {
  var phonenum = str.replace(/[^0-9]+/g,"");

  if(str.length===11 && str.indexOf(0)===0) {
    str = str;

  } else if (str.match(/[a-z]/i)) {
    str = phonenum;

  } else {
    str = "Not a phone number";
  }

  return str;
}

isItANum("hey");

Upvotes: 1

Views: 71

Answers (2)

abdul khodir
abdul khodir

Reputation: 129

At the second if, the variable str is already equal to "" . so you need to add another if the str doesnt have any numbers and the value of str is equal to "", its not a phone number.

function isItANum(str) {
var phonenum = str.replace(/[^0-9]+/g,"");

if(str.length===11 && str.indexOf(0)===0) {
 str = str;
} 
else if (str.match(/[a-z]/i)) {
  str = phonenum;
} 

if (str === '') {
  str = "Not a phone number";
}
console.log(str);
return str;
}

isItANum("hey");

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

Simply step through the calculation in order.

First, there are no digits in hey, so the variable phonenum gets replaced with an empty string when it reaches str.replace(/[^0-9]+/g, "");.

Second, you check if the length is 11, and if the first character isn't a 0. That fails, so it steps into the else if.

Third, hey matches the regex /[a-z]/i, so str is set to phonenum.

Fourth, str (now phonenum) gets returned, and is an empty string.

To actually return "Not a phone number", simply remove the else if entirely; the non-digits will already be stripped by the first regex. That way, when the if fails, it will go straight to the else. You can combine the length and starting 0 validation in the same conditional.

Note that you're probably actually looking for the regex /^[a-z]/i to ensure that it only contains lowercase characters (note the starting carat). And for what it's worth, the first if calculation is unnecessary, as str is already exactly equal to str.

This can be re-written as the following:

function isItANum(str) {
  var phonenum = str.replace(/[^0-9]+/g,"");
  if (str.length === 11 && str.indexOf(0) === 0 && str.match(/[^a-z]/i)) {
    str = phonenum;
  } else {
    str = "Not a phone number";
  }
  return(str);
}

console.log(isItANum("hey"));
console.log(isItANum("111111111"));
console.log(isItANum("01111111111"));

Hope this helps! :)

Upvotes: 2

Related Questions