Reverse a string preserving space positions | Javascript program to implement the above approach ; Initialize two pointers as two corners ; Move both pointers toward each other ; If character at start or end is space , ignore it ; If both are not spaces , do swap ; Driver code
function preserveSpace ( str ) { let n = str . length ; let start = 0 ; let end = n - 1 ; let Str = str . split ( ' ' ) ; while ( start < end ) { if ( Str [ start ] == ' ' ) { start ++ ; continue ; } else if ( Str [ end ] == ' ' ) { end -- ; continue ; } else { let temp = Str [ start ] ; Str [ start ] = Str [ end ] ; Str [ end ] = temp ; start ++ ; end -- ; } } document . write ( Str . join ( " " ) ) ; } let str = " " ; preserveSpace ( str ) ;