簡體   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