Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 += ' ';
    }
}
like image 923
Dari_we Avatar asked Mar 20 '26 13:03

Dari_we


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

like image 143
CertainPerformance Avatar answered Mar 23 '26 01:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!