I'm not sure if there is a simple way of doing this, but is there a way to find multiple instances in an unknown string? For example:
hellohellohellobyebyebyehello
Without knowing the value of the above string, can I return something that will tell me that there are 3 instances of "hello" and 3 instances of "bye" (I'm not worried about the last hello however as I'm looking for consecutive repetition. Thanks in advance!
Maybe the Sequitur algorithm can help: http://sequitur.info/
s = "hellohellohellobyebyebyehello"
s.replace(/(.+)(\1+)/g, function($0, $1) {
console.log($1 + " repeated " + ($0.length / $1.length) + " times");
});
"testhellohellohellobyebyebyehello".match(/(.+)\1+/)
This says : "match a sequence of at least 1 character (.+)
, then reference that first thing we found \1
at least one time +
or more.
It will return ["hellohellohello", "hello"]
meaning hellohellohello matches the full expression (expression 0), and "hello" matches expression 1 (the thing we reference with \1
).
Caveat:
something like "hahahaha"
will yield ["hahahaha", "haha"]
, instead of ["hahahaha", "ha"]
. so you'll need to use the above with some post-processing to get to your desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With