繁体   English   中英

仅在字符串的第一个单词中包括()

[英]Includes() only in the first word of a String

嗨,我只想在String的第一个单词上运行includes()方法。 我发现有一个可选参数fromIndex 我宁愿指定toIndex哪个值将是第一个空格的索引,但是似乎不存在这样的内容。

你有什么想法我能做到吗? 谢谢!

您已经说过要记住toIndex ,所以有两个选择:

  1. 使用indexOf代替:

     var n = str.indexOf(substr); if (n != -1 && n < toIndex) { // It's before `toIndex` } 
  2. 拆分第一个单词(使用splitsubstring或其他方式),然后在其上使用includes

     if (str.substring(0, toIndex).includes(substr)) { // It's before `toIndex` } 

(当然,根据您希望包含或排除它来调整上面的toIndex的用法。)

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

 myString = "This is my string"; firstWord = myString.split(" ")[0]; console.log("this doesn't include what I'm looking for".includes(firstWord)); console.log("This does".includes(firstWord)); 

您可以尝试以下方法并创建新方法

 let str = "abc abdf abcd"; String.prototype.includes2 = function(pattern,from =0,to = 0) { to = this.indexOf(' '); to = to >0?to: this.length(); return this.substring(from, to).includes(pattern); } console.log(str.includes2("abc",0,3)); console.log(str.includes2("abc",4,8)); console.log(str.includes2("abc")); console.log(str.includes2("abd")) 

您可以拆分字符串,然后将其传递给索引为0的include方法

 var a = "this is first word of a String"; console.log(a.includes(a.split(' ')[0])); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM