1

I have a string which displays a path. The issue is sometimes the path contains the same text more than once after the '/' as shown below. I want to ensure that if that happens, the content is removed. How can I solve this?

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
     const trimEnd = str => str.endsWith('/') ? str.slice(0, -1) :
                            str;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="FilePath" id="FilePath" value="/content/enforced/12063-CC-125/12063-CC-125/">
Spectric
  • 30,714
  • 6
  • 20
  • 43
Vzupo
  • 1,388
  • 1
  • 15
  • 34

1 Answers1

1

Split by /, get unique values with Set and the spread operator and join:

const str = "/content/enforced/12063-CC-125/12063-CC-125/";
const res = [...new Set(str.split("/"))].join('/');
console.log(res);
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • Is `Set` guaranteed to maintain the original ordering? – Barmar Jul 08 '21 at 19:19
  • @Barmar Apparently [it does](https://stackoverflow.com/questions/55460303/why-does-js-keep-insertion-order-in-set) – Spectric Jul 08 '21 at 19:21
  • 1
    I aslso assumed from the example that they only care about duplicates that are adjacent, but maybe that's not a concern. – Barmar Jul 08 '21 at 19:22