B
B
buymyopps2021-06-10 08:04:59
JavaScript
buymyopps, 2021-06-10 08:04:59

How to remove repetitions in a string?

Hello. There is such a line https://vk.comhttps://vk.comhttps://vk.com
How can I clean it from repetitions so that the output is https://vk.com?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-06-10
@buymyopps

Not optimally in the forehead, you can
choose the number of possible repetitions: from 2 to the length of the string, and should be divided without a remainder.
-- on each check: take a substring and compare with the rest of the same length
-- remember the found repetition, overwriting the previous one found, if any.
return either the last (and therefore shortest) repetition found, or the original string.

spoiler
function noRepeats(str) {
  const length = str.length;
  let result;
 
  search:
  for (let i = 2; i < length; i++) {
    if (length % i) continue;
    const slen = length / i;
    const sample = str.substr(0, slen);
    for (let j = 1; j < i; j++) {
      if (sample !== str.substr(j * slen, slen))
      	continue search;
    }
    
    result = sample;
  }
  
  return result.length ? result : str;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question