I'm trying to match a string which is only valid if all characters after the first occurrence of the target character, are also the the target character.
To better understand the structure, for example our target character is .
. The string is divided into two parts. The matching string has the following structure:
- substring without the target character
- substring with no other characters than the target character
Let's examine some examples:
""
// true - 1: "" doesn't contain target - 2: "" doesn't contain not target
"2"
// true - 1: "2" doesn't contain target - 2: "" doesn't contain not target
"."
// true - 1: "" doesn't contain target - 2: "." doesn't contain not target (only target)
"2.."
// true - 1: "2" doesn't contain target - 2: ".." doesn't contain not target (only target)
"...."
// true - 1: "" doesn't contain target - 2: "...." doesn't contain not target (only target)
"..2"
// false - 1: "..2" contains target - 2: "" doesn't contain not target
"2.2"
// false - 1: "2.2" contains target - 2: "" doesn't contain not target
"2.2."
// false - 1: "2.2" contains target - 2: "." doesn't contain not target (only target)
I was approaching the problem first with String methods (JS) by checking index of first occurrence, then counting number of occurrences, comparing with the length of string to check if there are any other characters between the ending, which was solving the problem, but wasn't looking too nice, and I don't think it's the most efficient way to solve the issue.
It looks like this:
const validate = (string, targetChar) => {
const firstTargetIndex = string.indexOf(targetChar);
if (firstTargetIndex === -1) return true; //no chance of not target following a target
const substringAfterFirstTarget = string.substr(firstTargetIndex);
const numberOfTargets = substringAfterFirstTarget.split(targetChar).length - 1;
return substringAfterFirstTarget.length === numberOfTargets;
}
Then I was researching regex methods to solve the problem, but I only found methods for checking occurrence, number of occurrence, if string ends with (even n times, but ignoring if there are occurrences between other characters), but couldn't figure a method to match the above test.