Elegant solution for undoing split('').join(' ');

Viewed 52

I'm wondering if there is an elegant solution for undoing this string manipulation:

'hello world'.split('').join(' '); // result: 'h e l l o   w o r l d'

My current solution is not elegant as the code that inserts spaces (the above code), in my opinion. It do work but can I do better?

let spaces = 'h e l l o   w o r l d'.split('  ');
let r = '';
for (let i = 0, len = spaces.length; i < len; ++i) {
    r += spaces[i].split(' ').join('');
    if (i != len - 1) {
        r += ' ';
    }
}
2 Answers

You can use a regex to match any character followed by a space, and replace with just that character:

console.log(
  'h e l l o   w o r l d'
    .replace(/(.) /g, '$1')
);

  • (.) - Match any character, put it in the first capture group
  • - Match a literal space
  • '$1' - Replace with the contents of the first capture group

You don't need to worry about multiple consecutive spaces in the input string messing up the logic because every subsequence of 2 characters will be matched one-by-one, and every second character is guaranteed to be a space added by the .join (except for the final character at the end of the string, which won't be matched by the regex).

Here is a functional programming way to perform the decoding (some consider functional style superior):

  1. split(' ') to create array of words
  2. map(word => word.replace(/ /g, '')) to remove spaces from each word
  3. join(' ') to combine the words into a string

const encoded = 'hello world'.split('').join(' ');

console.log(encoded); // 'h e l l o   w o r l d'

const decoded = encoded.split('  ')     // ['h e l l o', 'w o r l d']
  .map(word => word.replace(/ /g, ''))  // ['hello', 'world']
  .join(' ');                           // 'hello world'
  
 console.log(decoded);

Related