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 += ' ';
}
}
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 groupYou 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With