Search code examples
javascriptregexregexp-replaceregexp-substr

Replace all slashes on a line with a match on at the beginning of the same line


I'm trying to change all slashes on a line to replace with the 3-characters block at the beginninig of each line. (PMC,PAJ, etc in below example)

.PMC.89569XX/90051XX/90204XX/89533XX/90554XX/90053XX/90215XX/89874XX/89974XX/90481XX/90221XX/90508XX/90183XX/88526XX/89843XX/88041XX/90446XX/88515XX/89574XX/89847XX/88616XX/90513XX/90015XX/90334XX/89649XX.T00
.PAJ.77998XX/77896XX.T00 .PAG.78116XX/78104XX/77682XX/07616XX/77663XX/77863XX/07634XX/78088XX/77746XX/78148XX.T00 .PKC.22762XX/22358XX/22055XX/22672XX/22684XX/22154XX/22608XX/22768XX/22632XX/22266XX/22714XX/22658XX/22631XX/22288XX/22020XX/22735XX/22269XX/22138XX/22331XX/22387XX/22070XX/22636XX/22629XX/22487XX/22725XX.T00

The desired outcome should be:

PMC.89569XXPMC90051XXPMC90204XXPMC89533XXPMC90554XXPMC90053XXPMC90215XXPMC89874XXPMC89974XXPMC90481XXPMC90221XXPMC90508XXPMC90183XXPMC88526XXPMC89843XXPMC88041XXPMC90446XXPMC88515XXPMC89574XXPMC89847XXPMC88616XXPMC90513XXPMC90015XXPMC90334XXPMC89649XX.T00

I'm not sure how to accomplish this. This is what I have so far:

 (.)([A-Z]{3})(.)(\/)

Solution

  • If you only plan to support ECMAScript 2018 and newer, you may achieve what you need with a single regex:

    .replace(/(?<=^\.([^.]+)\..*?)\//g, "$1")
    

    See the regex demo.

    Details

    • (?<=^\.([^.]+)\..*?) - a positive lookbehind that, immediately to left of the current location, requires
      • ^ - start of string
      • \. - a dot
      • ([^.]+) - Group 1: one or more chars other than a dot
      • \. - a dot
      • .*? - any 0+ chars, other than linebreak chars, as few as possible
    • \/ - a / char.

    JS demo:

    var strs = ['.PMC.89569XX/90051XX/90204XX/89533XX/90554XX/90053XX/90215XX/89874XX/89974XX/90481XX/90221XX/90508XX/90183XX/88526XX/89843XX/88041XX/90446XX/88515XX/89574XX/89847XX/88616XX/90513XX/90015XX/90334XX/89649XX.T00','.PAJ.77998XX/77896XX.T00','.PAG.78116XX/78104XX/77682XX/07616XX/77663XX/77863XX/07634XX/78088XX/77746XX/78148XX.T00','.PKC.22762XX/22358XX/22055XX/22672XX/22684XX/22154XX/22608XX/22768XX/22632XX/22266XX/22714XX/22658XX/22631XX/22288XX/22020XX/22735XX/22269XX/22138XX/22331XX/22387XX/22070XX/22636XX/22629XX/22487XX/22725XX.T00'];
    for (var s of strs) {
     console.log(s.replace(/(?<=^\.([^.]+)\..*?)\//g, "$1"));
    }