Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you move n characters that are between 2 words to the end of the line (inside of a multi-line string)?

The multi-line string always contains XY, followed by a few characters (not always the same amount of characters), followed by :thiSWORD:

The goal is to move these few characters that are in the middle to the end of the line

So, for example, this is the original string:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

XY1239:thiSWORD:a6b4ba21ba54f6bde411930b0d88432f
XY545:thiSWORD:b598944d1ba4c787e411800b8043559c
XY4239:thiSWORD:a6b4ba21ba54f6bde411930b0d8817c6

In the end it would look like this:

XY:thiSWORD:a6b4ba21ba54f6bde411930b0d88432f1239
XY:thiSWORD:b598944d1ba4c787e411800b8043559c545
XY:thiSWORD:a6b4ba21ba54f6bde411930b0d8817c64239

I have tried something along the lines of

str.replace(/(\w{4})(\w{48})/g, '$2$1');

But that only moved 4 characters, so lines that had 3 or 5 characters between XY and :thiSWORD: were messed up.

>Solution :

You can use 2 capture groups, and use those in the replacement:

XY(\d+)(.*)
  • XY Match literally
  • (\d+) Capture 1+ digits in group 1
  • (.*) Capture the rest of the line in group 2

See a regex demo.

[
  "XY1239:thiSWORD:a6b4ba21ba54f6bde411930b0d88432f",
  "XY545:thiSWORD:b598944d1ba4c787e411800b8043559c",
  "XY4239:thiSWORD:a6b4ba21ba54f6bde411930b0d8817c6"
].forEach(s => {
  console.log(s.replace(/XY(\d+)(.*)/, "XY$2$1"))

})

Another variant using 1 or more word characters \w+ if there can also be word characters instead of only digits, matching 32 word chars instead of 48, word boundaries on the left and right and matching :thiSWORD:

\bXY(\w+)(:thiSWORD:\w{32})\b

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading