patternjavascriptMinor
Finding patterns in a string
Viewed 0 times
stringpatternsfinding
Problem
I'm trying to find patterns of different length in a given string. How can I improve it? Are there problems?
function find(pattern,str) {
var arr = [];
for (i= 0;i<str.length;i++) {
if(pattern== str.slice(i,pattern.length+i)) {
arr.push([i,pattern.length-1+i]);
};
};
if(!arr.length) { return false;} else { return arr;};
};
find('abfd','abfdffdabfdfaffab');Solution
Here are two different ways of doing this, one using repeated calls to
The
.indexOf() and one using repeated calls with a regex to .exec(). The regex solution requires the pattern argument to be a regex compatible string or an actual RegExp object with the g flag on it.The
.indexOf() option should be much faster than what you have since it avoids repeated .slice() operations and .indexOf() as a library function should be faster than your own variation. The regex option is a lot more flexible since you can search for phrases that match a regular expression.function find1(pattern,str) {
var arr = [];
var i = 0;
while ((i = str.indexOf(pattern, i)) > -1) {
// got a match starting at i
arr.push([i, i + pattern.length - 1]);
i++;
}
return arr.length ? arr : false;
};
function find2(pattern,str) {
var arr = [], matches;
if (typeof pattern === "string") {
pattern = new RegExp(pattern, "g");
} else if (!(pattern instanceof RegExp)) {
throw new Error("pattern must be string or RegExp object");
}
while (matches = pattern.exec(str)) {
arr.push([matches.index, matches.index + matches[0].length - 1]);
}
return arr.length ? arr : false;
};
document.getElementById("run1").addEventListener("click", function(e) {
var results = find1('abfd','abfdffdabfdfaffab');
log(results);
});
document.getElementById("run2").addEventListener("click", function(e) {
var results = find2('abfd','abfdffdabfdfaffab');
log(results);
});
function log(x) {
var d = document.createElement("div");
d.innerHTML = JSON.stringify(x) + "
";
document.body.appendChild(d);
}
Run .indexOf()
Run regex
Context
StackExchange Code Review Q#104765, answer score: 2
Revisions (0)
No revisions yet.