Checking if Javascript .split() fails

Viewed 21606

I have the following function:

var checkCode=function(codeString){
  var ifs=codeString.split("if");
  ...
}

Is there a way to check if the code fails, as in does not find any if strings to split from in the codeString that is input to the function?

7 Answers

Old topic but it may help someone.

I would use a try catch

let ifs: string;
try {
  ifs = codeString.split("if");
} catch {
  // the code fails
}

And inside a function

var checkCode = function(codeString): string{
  try {
    return codeString.split("if");
  } catch {
    return null;
  }
}

Using ES6 destructuring:

  const canSplit = (input = '', delimiter) => {
    const [, second] = input.split(delimiter) || ''
    return second !== undefined
  }

At first I wanted to use just return !!second but then canSplit("abc-", '-') would return false.

Related