0

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?

8
  • The code you posted should work, what's the problem you're running into? Commented Sep 1, 2022 at 0:30
  • Why don't you do str.indexOf("test") === 0 or === 10? Commented Sep 1, 2022 at 0:32
  • It returns true regardless of what number I put as the second argument. Commented Sep 1, 2022 at 0:32
  • Yeah the position parameter only indicates where to start searching, not whether the item only exists at that index. indexOf(), lastIndexOf(), or matchAll() may be more helpful for whatever your use case is. Commented Sep 1, 2022 at 0:35
  • How about str.slice(10).startsWith('test')? Commented Sep 1, 2022 at 0:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, "The slice() method does not change the original string." - w3schools.com/jsref/jsref_slice_string.asp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.