Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading