Search code examples
javascriptregexp-replace

need Regexp which leave only two dashes in a string


i have a string like d333-4444-555--5---5-
and want catch only two first dashes and get 333-4444-55555
if it will be first two and two in a row, two becomes one like: d333--4444-555--5---5- goes 333-4444-55555

any advice or ready solvation

i started with console.log('d-45----'.replace(/[^0-9]/g, '')) but it's very far from what i expect two days on the same point

Thank you


Solution

  • You can do multiple replacements to sanitize the string.

    • First replace all the 2 or more hyphens with a single hyphen as you don't know how many and where in the string you have double occurrences

    • Then replace all non digits except for hyphens with an empty string, and remove the hyphens at the start and at the end of the string

    • When you have the sanitized string, capture the first parts with 2 hyphens and in the last parts remove all hyphens

    [
      "d333-4444-555--5---5-",
      "d333--4444-555--5---5-",
      "----d333--4444-555--5---5----",
      "d333--4444",
      "d333-4444",
      "d333"
    ].forEach(s => {
      const res = s
        .replace(/-{2,}/g, "-")
        .replace(/[^\d-]+|^-|-$/g, "")
        .replace(/^(\d+-\d+-)(\d[\d-]*)/, (_, g1, g2) => g1 + g2.replace(/-/g, ""))
      console.log(res);
    })

    Another option with split and reduce:

    [
      "d333-4444-555--5---5-",
      "d333--4444-555--5---5-",
      "----d333--4444-555--5---5----",
      "d333--4444",
      "d333-4444",
      "d333"
    ].forEach(s => {
      const res = s
        .replace(/[^\d-]+/, "")
        .split(/-+/)
        .filter(Boolean)
        .reduce((a, c, i) => i < 2 ? a + "-" + c : a + c)
      console.log(res)
    })