Search code examples
javascriptif-statementreturnalphanumeric

Return Alphanumerics -issue with combining pieces of the function


Submitted earlier about this, at this point all the pieces work separately, but not together. I've tried moving things around to see if it was simply an order issue, but that didn't fixe it. Trying to put them in one big if/else also didn't seem to work. I can either get the string to display only alphanumerics characters OR display 'not a string', but I cannot get the code to work to do both. This section will return the proper alphanumerics only:

function nothingSpecial(str) {
  var re = /[A-Z\s0-9]/i;
  var newStr = '';

  for(var i=0; i<str.length; i++){
    if (re.test(str[i])){
      newStr = newStr + str[i];
    }
  }
   return newStr;
   if(str.length <= 0) {
    return ("Not a string!");
  }

      if (typeof str !== String) {
        return "Not a string!"} 

    }

nothingSpecial("asdfalsd@#$#")

This will return "not a string!", even if it should show alphanumerics, but is correct or seemingly so for numbers and ""

function nothingSpecial(str) {

  var re = /[A-Z\s0-9]/i;
  var newStr = '';

    if(str.length <= 0) {
    return ("Not a string!");
  }

  if (typeof str !== String) {
    return "Not a string!"} 

  for(var i=0; i<str.length; i++){
    if (re.test(str[i])){
      newStr = newStr + str[i];
    }
  }
   return newStr;

    }
nothingSpecial(23)

What am I doing wrong? -Thank you in advance!


Solution

  • Edit: Okay, based on your comment, here you go:

    This is your problem:

    if (typeof str !== String)
    

    You're comparing the result of typeof str, which is a string, with the object constructor for strings, String, which is a function. It's failing because you're not actually checking for a string, you're comparing a string (the output of typeof, which is always a string regardless of the type you're checking) with a function. Your comparison should instead look like this:

    if (typeof str !== 'string')
    

    Edit: Heres a JSFiddle.