检查 Javascript .split() 是否失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20578775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:48:54  来源:igfitidea点击:

Checking if Javascript .split() fails

javascriptsplit

提问by Zach Brantmeier

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 ifstrings to split from in the codeStringthat is input to the function?

有没有办法检查代码是否失败,因为在函数的输入中找不到任何if要拆分的字符串codeString

回答by Pointy

If the length of the result is 1, then the split didn't split.

如果结果的长度为 1,则拆分未拆分。

回答by Joseph

It will return an array with the whole string as the only entry.

它将返回一个以整个字符串作为唯一条目的数组。

if(codeString === ifs[0]) //nothing was split

回答by SimoAmi

It looks like all you want is to check if the function splits and return a boolean state of that action. If so, here's a simple checker:

看起来您想要的只是检查函数是否拆分并返回该操作的布尔状态。如果是这样,这是一个简单的检查器:

var canSplit = function(str, token){
    return (str || '').split(token).length > 1;         
}

and use as follows:

并使用如下:

canSplit('test if this works', 'if'); // returns true

canSplit('test that this fails', 'if'); // returns false

回答by Ringo

Try this:

试试这个:

 var checkCode=function(codeString){
      var ifs = codeString.split("if");
         if(ifs.length == 1){ alert('no split'); } 
         else{ alert('splitted'); }
         return ifs;
    }
var str = "dfsdfif";
checkCode(str);

回答by Ajay Gupta

You can try includesmethod of String.prototype. Just like below example.

你可以试试 的includes方法String.prototype。就像下面的例子。

var your_var = codeString.includes("if");//return true or false

It returns trueif a string contains specified character else returns false. According to trueor false, you can take the decision if you want to splitstring or not.

它返回true一个字符串包含指定的字符否则返回false。根据truefalse,您可以决定是否要split串连。

回答by rbalet

Old topic but it may help someone.

旧话题,但它可能对某人有所帮助。

I would use a try catch

我会使用 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;
  }
}

回答by Yos

Using ES6destructuring:

使用ES6解构:

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

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

起初我想使用 justreturn !!second但后来canSplit("abc-", '-')会返回 false。