sempre che il tuo problema sia il fatto che non ti funziona
il problema e che sostituisce.


così dovrebbe andare

codice:
testo = "ygyu hbviuv jhvuv uvuiv iviuvu";
while(testo.indexOf(' ') != -1)
{
testo = testo.replace(" ","_");
}

document.write(testo);