Check if a String Contains a Substring with includes() in JavaScript
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
The String.prototype.includes() method checks whether one string appears inside another and returns a Boolean value. In the example, containsSubstring(text, substring) first validates that both arguments are strings, then returns text.includes(substring). This makes the helper safe to call with expected string inputs and easy to reuse.
Inputs: text is the original string to search, and substring is the value to look for. You can also call includes() directly with an optional second argument, position, which specifies the index at which to begin searching. Output: true if the substring is found; otherwise false.
The method is case-sensitive, so 'JavaScript' and 'javascript' are different. If you want a case-insensitive check, convert both strings to lowercase before calling includes(). The optional start index does not affect the returned value's meaning: it only limits where the search begins.
Time complexity: worst-case O(n × m), where n is the length of the searched string and m is the length of the substring. Auxiliary space is O(1), excluding any internal engine optimizations. For everyday substring checks, includes() is clear, readable, and normally fast.