Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

};

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!