'Cleaner way to remove 2nd word from string. Currently using split, splice, then join

I have a function to always remove the 2nd word from a sentence.

public cleanMessage(message) {
    let cleanedMessage: any = message.split(' ');
    cleanedMessage.splice(1, 1);
    cleanedMessage = cleanedMessage.join(' ');
    return cleanedMessage;
  }

cleanMessage('Hello there world')
// outputs 'Hello world'

Is there a cleaner way of doing this?



Solution 1:[1]

Regexp is indeed shorter and IMO easier to read as long as you use simpler operators.

string.replace(/^(\S+)\s+\S+/, '$1')
^ from beginning of string
(\S+) take and remember non-spaces - 1st word
\s+ followed by spaces
\S+ and another word
$1 replace with remembered first word

Solution 2:[2]

What you wrote is already pretty much as clean as possible.

You could write it a little shorter maybe like:

public cleanMessage = (message) => message
  .split(' ')
  .filter((word, i) => i !== 1)
  .join(' ');

Solution 3:[3]

I like the regexp solutions, but here's another one that's kind of obvious.

const cleanMessage = (message) => {
  const [first, second, ...rest] = message.split(' ');
  return [first, rest].flat().join(' ');
};

console.log(cleanMessage("Hello world, I'm here!"));
.as-console-wrapper{min-height: 100%!important; top: 0}

Solution 4:[4]

One more potential way using Array reduce:

const cleanMessage = message => (
  message.split(' ').reduce(
    (f, i, idx) => idx === 1 ? f : f + ' ' + i, ''
  )
);

Explanation

  • Use split to obtain an array of words (ie, separated by space)
  • Use reduce to iterate through the words and skip the word at index 1.

Code snippet

const cleanMessage = message => (
  message.split(' ').reduce(
    (f, i, idx) => idx === 1 ? f : f + ' ' + i
  )
);

console.log(cleanMessage('Hello there world!'));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oleg V. Volkov
Solution 2 Mike Jerred
Solution 3
Solution 4 jsN00b