Home > Enterprise >  JavaScript string.includes() method at specific index, without modifying original string?
JavaScript string.includes() method at specific index, without modifying original string?

Time:09-01

I am wondering if there's a way to use the str.includes() function in JavaScript, but check at a certain index of the string, without changing the original string. For example:

var str = "this is a test";
str.includes("test");     //returns true
str.includes("test", 0)   //returns false, as "test" is not at position 0
str.includes("test", 10)  //returns true, as "test" is at position 10 in the string

I've been trying to find a way to do this, but haven't been able to figure it out. Could somebody please help me?

CodePudding user response:

String.prototype.includes() has something close to this functionality, as argument 2 is taken as the start position for searching.

If you want to search at, not after, a specific index, you can write a function that takes the string, creates a slice of it, and checks if that slice matches

function substring_at(string, substring, position) {
  let slice = string.slice(position, position   substring.length)
  
  // Triple equals removes type coercion support, and is slightly faster
  return slice === substring
}

I've tested it with your examples and all seems well.

  • Related