I've changed it to val.replace(' ', '_') which should take pretty much exactly the same amount of time as val.indexOf(' ').

This is in a function updateValue() that is only called on keyup.