Hi I would like to run includes()
method only on the first word of a String. I have found that there is an optional parameter 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.
Do you have any idea how I could achieve this? Thanks!
You've said you have a toIndex
in mind, so two options:
Use indexOf
instead:
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:
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.)
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
var a = "this is first word of a String"; console.log(a.includes(a.split(' ')[0]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.