3

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 += ' ';
    }
}
Dari_we
  • 111
  • 8
  • 1
    I will say better to store the original string in a variable. Not sure if you have a specific usecase. – A Paul Dec 25 '20 at 18:21
  • @APaul That's not possible if it were I would indeed do that. It's the beginning of an obfuscation function of text. To work around censorship. I'm planning on adding as many various ways to obfuscate text as possible. Even multiple levels. Since sites can only spend a certain amount of cpu time to analyze the text this will indeed irritate them. If you have any suggestions I'm listening. – Dari_we Dec 25 '20 at 19:07
  • check this, if this helps on your obfuscation functionhttps://stackoverflow.com/questions/14458819/simplest-way-to-obfuscate-and-deobfuscate-a-string-in-javascript – A Paul Dec 25 '20 at 19:37
  • also see https://stackoverflow.com/questions/58537023/obfuscate-text-using-javascript – A Paul Dec 25 '20 at 19:38

2 Answers2

5

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).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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);
terrymorse
  • 6,771
  • 1
  • 21
  • 27