Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 仅在字符串的第一个字中包含()_Javascript_String_Methods - Fatal编程技术网

Javascript 仅在字符串的第一个字中包含()

Javascript 仅在字符串的第一个字中包含(),javascript,string,methods,Javascript,String,Methods,您好,我只想在字符串的第一个字上运行includes()方法。我发现有一个可选参数fromIndex。我更愿意指定toIndex哪个值将是第一个空格的索引,但类似的东西似乎不存在 你知道我怎样才能做到这一点吗?谢谢 您说过您心中有一个toIndex,所以有两个选择: 改用indexOf: var n = str.indexOf(substr); if (n != -1 && n < toIndex) { // It's before `toIndex` } (当

您好,我只想在字符串的第一个字上运行
includes()
方法。我发现有一个可选参数
fromIndex
。我更愿意指定
toIndex
哪个值将是第一个空格的索引,但类似的东西似乎不存在


你知道我怎样才能做到这一点吗?谢谢

您说过您心中有一个
toIndex
,所以有两个选择:

  • 改用
    indexOf

    var n = str.indexOf(substr);
    if (n != -1 && n < toIndex) {
        // It's before `toIndex`
    }
    

  • (当然,根据您想要的是包含还是排除,调整上述
    到索引的使用。)

    如果它是一个句子,只需拆分字符串即可获得第一个单词

    myString=“这是我的字符串”;
    firstWord=myString.split(“”[0];
    log(“这不包括我要找的内容”。包括(第一个单词));
    
    log(“This does.”包括(firstWord))您可以尝试以下方法并创建一个新方法

    让str=“abc abdf abcd”; String.prototype.includes2=函数(模式,from=0,to=0){ to=该指数(“”); to=to>0?to:this.length(); 返回此.substring(from,to).includes(pattern); } 控制台日志(str.includes2(“abc”,0,3)); 控制台日志(str.includes2(“abc”,4,8)); 控制台日志(str.includes2(“abc”);
    log(str.includes2(“abd”)
    您可以拆分字符串并传递给索引为0的include方法

    var a=“这是字符串的第一个单词”;
    
    控制台日志(a.包括(a.拆分(“”)[0])请添加一些测试用例和您的努力
    if (str.substring(0, toIndex).includes(substr)) {
        // It's before `toIndex`
    }