I am writing a function that takes two strings as input parameters: text and pattern.
If
textends with a substring starting at indexindexand this substring is a start ofpattern, then returnindex.If there is no such substring, return
-1.
I've come up with the following function, but I wonder if there is more efficient solution.
So the question is: is there more efficient algorithm to find such substrings?
function findSubstring(text, pattern) {
let index = -1;
for (let i = 1; i <= text.length; i++) {
const tail = text.substr(-i);
if (pattern.indexOf(tail) === 0) {
index = text.length - i;
}
}
return index;
}
const exampleText = 'const result = items.m';
const examplePattern = '.map((item) => {})';
console.log(findSubstring(exampleText, examplePattern)); // -> 20