Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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+/, '');
}
about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report

0

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(' ');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!