Home > Software design >  How do you move the first n characters of every line in a string to the end of the same line (not to
How do you move the first n characters of every line in a string to the end of the same line (not to

Time:11-06

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

CodePudding user response:

const str = document.querySelector('div')

  // Get the text (from wherever)
  .textContent

  // Split on the line-break
  .split('\n')

  // Filter out empty strings
  .filter(l => l.length)

  // Map over the array that `filter` returns
  // and move the characters around
  .map(str => `${str.slice(-4)}${str.slice(0, -4)}`)

  // Join the array up with line breaks
  .join('\n');

console.log(str);
<div>
1234a6b4ba21ba54f6bde411930b0b1ec6df
3124a6b4ba21ba54f6bde411930b0b1ef248
2134a6b4ba21ba54f6bde411900b89f7dcf3
4123a6b4ba21ba54f6bde411920bbf835b60
</div>

CodePudding user response:

Split the string into lines and then rejoin them later:

const string = `\
1234a6b4ba21ba54f6bde411930b0b1ec6df
3124a6b4ba21ba54f6bde411930b0b1ef248
2134a6b4ba21ba54f6bde411900b89f7dcf3
4123a6b4ba21ba54f6bde411920bbf835b60`;

const result = string
  .split("\n")
  .map((line) => line.substring(4)   line.substring(0, 4))
  .join("\n");
  
console.log(result);

  • Related