How to add elements at the beginning of a String. Similar to JS unshift();

Hello !
I have an unknown size String, but with a maximum size of 8 and I want to make sure it’s size will always be 8 by adding 0(zeroes) at the beginning of the String.
For example the inputted String is “5687” and I have to add 0 until it’s size is 8: “00005687”.

String str = "5687";
while(str.length() < 9) {
  // add 0 at the beginning of str

Unlike JavaScript, Arduino C++ doesn’t have anything like unshift() or does it ?

How can I achieve my goal ? Thank you.

P.S: I am using an ESP32 and only a couple of Strings, because the handler of ESPAsyncWebServer usually return String parameters.

String str = "5687";

void setup()
   while (str.length() < 8)
      str = "0" + str;

void loop()

I didn't think it would be that easy.

I have one question though: why didn't you use "String('0')" instead of "0"?

you can use sprintf to format numeric values with a specific # of digits, with or without leading zeros.

the following is for a char array string, not a C++ String and a string is terminated by a NULL character so an 8 character string has 9 bytes

loop (void)
    int  val = 1234;
    char s   [20];

    sprintf (s, "%08d", val);
    Serial.println (s);

…but that’s not a great solution if the numbers are already in a String.