[英]Includes() only in the first word of a String
Hi I would like to run includes()
method only on the first word of a String. 嗨,我只想在String的第一个单词上运行
includes()
方法。 I have found that there is an optional parameter fromIndex
. 我发现有一个可选参数
fromIndex
。 I would rather need to specify toIndex
which value would be the index of first whitespace but something like that does not seem to exist. 我宁愿指定
toIndex
哪个值将是第一个空格的索引,但是似乎不存在这样的内容。
Do you have any idea how I could achieve this? 你有什么想法我能做到吗? Thanks!
谢谢!
You've said you have a toIndex
in mind, so two options: 您已经说过要记住
toIndex
,所以有两个选择:
Use indexOf
instead: 使用
indexOf
代替:
var n = str.indexOf(substr); if (n != -1 && n < toIndex) { // It's before `toIndex` }
Split off the first word (using split
or substring
or whatever) and then use includes
on it: 拆分第一个单词(使用
split
或substring
或其他方式),然后在其上使用includes
:
if (str.substring(0, toIndex).includes(substr)) { // It's before `toIndex` }
(Adjust the use of toIndex
above based on whether you want it inclusive or exclusive, of course.) (当然,根据您希望包含或排除它来调整上面的
toIndex
的用法。)
If it's a sentence, just split the string to get the first word 如果是句子,只需将字符串拆分即可得到第一个单词
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));
You can try the following approach and create a new method 您可以尝试以下方法并创建新方法
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"))
You can split your string and pass to the include method with index 0 您可以拆分字符串,然后将其传递给索引为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.