Home > Back-end >  Check if a string is made up of multiple occurences of a substring
Check if a string is made up of multiple occurences of a substring

Time:06-27

(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
Could someone help me out?

CodePudding user response:

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
};

};

CodePudding user response:

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)}`))

CodePudding user response:

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.

CodePudding user response:

I highly recommend sharpening your algorithm skills on a site like leetcode.com

Here's what I came up with

function checkString(whole, sub) {
  for (let i = 0; i < whole.length - 1; i  ) {
    if (whole[i] !== sub[i % sub.length]) {
      return false;
    }
  }
  return true;
}
  • Related