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

Time:01-28

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?

CodePudding user response:

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(' ');

CodePudding user response:

If you're just looking to shorten it, you can use regex:

(?<=\S)\s\S will take out the second word in the string

  • (?<=\S) creates a lookbehind for a word
  • \s\S selects a space with a word after it

You can then remove this space word with:

public cleanMessage(message) {
  return message.replace(/(?<=\S)\s\S /, '');
}

CodePudding user response:

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
  •  Tags:  
  • Related