Search code examples
javascriptstringsubstring

How do you move the first n characters of every line in a string to the end of the same line (not to end of string)?


The string fileString contains multiple lines of characters, like this:

1234a6b4ba21ba54f6bde411930b0b1ec6df
3124a6b4ba21ba54f6bde411930b0b1ef248
2134a6b4ba21ba54f6bde411900b89f7dcf3
4123a6b4ba21ba54f6bde411920bbf835b60

I'd like to move the first 4 characters of every line to the end of its respective line, like this:

a6b4ba21ba54f6bde411930b0b1ec6df1234
a6b4ba21ba54f6bde411930b0b1ef2483124
a6b4ba21ba54f6bde411900b89f7dcf32134
a6b4ba21ba54f6bde411920bbf835b604123

I saw another post with a proposed solution, but that code moves the first 4 characters of the string to the end of the string, which is not what I'm trying to do.

So with this code:

var num = 4
fileString = fileString.substring(num) + fileString.substring(0, num)

The initial string stated above turns into this:

a6b4ba21ba54f6bde411930b0b1ec6df
3124a6b4ba21ba54f6bde411930b0b1ef248
2134a6b4ba21ba54f6bde411900b89f7dcf3
4123a6b4ba21ba54f6bde411920bbf835b60
1234

Solution

  • No need for array manipulations

    A simple String.replace() using regex capture groups seems to provide the shortest solution:

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

    Definitions

    1. () = defines the capture groups
    2. \w = select alphanumeric characters
    3. {n} = takes n characters
    4. $n = tokens representing the unnamed capture groups in sequence

    And "$2$1" is creating a replacement string by appending the text of the first capture group to the end of the second.

    For more details see: regex101 Fiddle

    Snippet

    Try the code to see how it works. You may also add brackets and spaces around the numbers and it works the same.

    stdout.value = stdin.value.replace(/(\w{4})(\w{32})/g, '$2$1');
    textarea {
      width: 80%;
      height: 5rem;
      display: block;
      margin-bottom: 1rem;
      background-color: aliceblue;
    }
    Input:
    <textarea id="stdin">
    1234a6b4ba21ba54f6bde411930b0b1ec6df
    3124a6b4ba21ba54f6bde411930b0b1ef248
    2134a6b4ba21ba54f6bde411900b89f7dcf3
    4123a6b4ba21ba54f6bde411920bbf835b60
    </textarea>
    
    Output:
    <textarea id="stdout"></textarea>