Reverse a string preserving space positions | Function to reverse the string and preserve the space position ; Mark spaces in result ; Traverse input string from beginning and put characters in result from end ; Ignore spaces in input string ; ignore spaces in result . ; driver function
function reverses ( str ) { let inputArray = str . split ( " " ) ; let result = new Array ( inputArray . length ) ; for ( let i = 0 ; i < inputArray . length ; i ++ ) { if ( inputArray [ i ] == ' ' ) { result [ i ] = ' ' ; } } let j = result . length - 1 ; for ( let i = 0 ; i < inputArray . length ; i ++ ) { if ( inputArray [ i ] != ' ' ) { if ( result [ j ] == ' ' ) { j -- ; } result [ j ] = inputArray [ i ] ; j -- ; } } document . write ( ( result ) . join ( " " ) ) ; } reverses ( " " ) ;