bjeelaa
bjeelaa

Reputation: 33

Check if a string is made up of multiple occurences of a substring

(JavaScript) So, I need a function checkString(str, substr) that checks whether a string is made out of multiple occurences of a given substring.
Examples:
checkString("abc", "abc") -> true
checkString("abcabcabc", "abc") -> true
checkString("abcdef", "abc") -> false
checkString("abcab", "abc) -> true
Could someone help me out?

Upvotes: 3

Views: 94

Answers (3)

Cristian-Florin Calina
Cristian-Florin Calina

Reputation: 1008

If whitespaces don't matter, this is a solution:

const checkString = (bigString, subString) => {
  const split = bigString.split(subString);
  const onlyOccurances = split.filter(v => v === '');

  return split.length === onlyOccurances.length
}

checkString("abc", "abc") // true
checkString("abcabcabc", "abc") // true
checkString("abcdef", "abc") // false

bigString.split(subString) will split the big string into an array of empty strings if there's perfect match, and the length of it will be exactly how many occurances there are. If any of the values in the array are not empty strings, it means there is not a perfect match so there will be a difference between the length of the filtered by empty and the length of the splited values.

Hope it makes sense.

Upvotes: 1

Carsten Massmann
Carsten Massmann

Reputation: 28206

This would be one way to check against the pattern abc:

const rx=/^(abc)+$/;
console.log(["abc","abcabcabc","abcdef"].map(t=>
 `${t} ${rx.test(t)}`))

Upvotes: 0

Johnny Major
Johnny Major

Reputation: 228

This method will return an object and found will be true if the value is found in the string and multipleFound will be true if found more than once;

const checkString = function(str, v) {
let found = false,
    multi = false,
    index;
index = str.indexOf(v);
if (index !== -1) {
    found = true;
    index = str.indexOf(v, index + v.length);
    if (index !== -1) {
        multi = true;
    }
}
return {
    found : found,
    multipleFound : multi
};

};

Upvotes: 0

Related Questions