You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改自定义JavaScript函数,使其字符匹配失败时返回null?

解决方法

你需要先判断目标字符是否存在于参数字符串中。因为indexOf()方法在找不到指定字符时会返回-1,而substring(-1)会直接返回整个原字符串,这就是第二个输出不是null的原因。

修改后的函数逻辑如下:

function my_strchr(param_1, param_2){
    const pos = param_1.indexOf(param_2);
    // 找不到目标字符时返回null
    if (pos === -1) {
        return null;
    }
    // 找到则返回从该位置开始的子串
    return param_1.substring(pos);
};

console.log(my_strchr("asdfasdf", "s")); // 输出 "sdfasdf"
console.log(my_strchr("asdf", "g")); // 输出 null

核心改动点:

  • 把indexOf的结果存入变量pos,便于后续判断
  • 增加判断逻辑:当pos等于-1(未找到目标字符)时,直接返回null
  • 仅在找到目标字符时,返回对应位置开始的子串

内容的提问来源于stack exchange,提问作者arsinic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:50:38