javascriptstringreplacereplaceall

Replacing spaces in a complex string in JS


var generated_pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEY17rXBY86d3b e2e70cf35bc6b9490 0a0e76a27a9fc15e769 d674e3a9ce7d6bad5== =G4p6 -----END PGP PUBLIC KEY BLOCK----- "

I want to replace the space that comes after "-----BEGIN PGP PUBLIC KEY BLOCK-----" with \n\n and replace all other spaces with 1 \n while keeping the spaces between the wording “ -----BEGIN PGP PUBLIC KEY BLOCK-----” without any replacement also keeping “END PGP PUBLIC KEY BLOCK”

So the result becomes:

"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nxjMEY17rXBY86d3b\ne2e70cf35bc6b9490\n0a0e76a27a9fc15e769\nd674e3a9ce7d6bad5==\n=G4p6\n-----END PGP PUBLIC KEY BLOCK-----\n" 

Note: The public key generated will be random.The double \n\n will always be installed after the first “BLOCK-----“ as shown above, the public key string will always end with a space that should be replaced with a single \n while other spaces will be replaced with single \n.

I have already tried:

generated_pubkey.replaceAll(" ", "\n")

But that replaced even the spacing between the wording of BEGIN PGP etc and END PGP etc


Solution

  • First can replace '-----BEGIN PGP PUBLIC KEY BLOCK----- ' (one space) with '-----BEGIN PGP PUBLIC KEY BLOCK----- ' (two spaces ) using .replace().

    Then, all you need to do is create a simple function to toggle between new lines or spaces depending on whether or not it is between two -----s

    function replaceSpaces(str) {
      let ret = "";
      let isOn = true;
      for (const tok of str.split(' ')) {
        if (tok.includes('-----')) isOn = !isOn;
        if (isOn) ret += tok + '\n';
        else ret += tok + ' ';
      }
      return ret;
    }
    
    let generated_pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEY17rXBY86d3b e2e70cf35bc6b9490 0a0e76a27a9fc15e769 d674e3a9ce7d6bad5== =G4p6 -----END PGP PUBLIC KEY BLOCK----- ";
    generated_pubkey = generated_pubkey.replace('-----BEGIN PGP PUBLIC KEY BLOCK----- ', '-----BEGIN PGP PUBLIC KEY BLOCK-----  ')
    const new_pubkey = replaceSpaces(generated_pubkey);
    
    console.log(new_pubkey);