我有以下功能:
var checkCode=function(codeString){
var ifs=codeString.split("if");
...
}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以检查代码是否失败,因为在函数输入中找不到if要拆分的字符串codeString?
它将返回一个数组,其中整个字符串作为唯一的条目。
if(codeString === ifs[0]) //nothing was split
Run Code Online (Sandbox Code Playgroud)
看起来您想要的只是检查函数是否拆分并返回该操作的布尔状态。如果是这样,这是一个简单的检查器:
var canSplit = function(str, token){
return (str || '').split(token).length > 1;
}
Run Code Online (Sandbox Code Playgroud)
并使用如下:
canSplit('test if this works', 'if'); // returns true
canSplit('test that this fails', 'if'); // returns false
Run Code Online (Sandbox Code Playgroud)