Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to remove the last word from a string in Node.js

2 Answers

0 votes
function removeLastWord(s) {
    const indexOfLastSpace = s.lastIndexOf(' ');

    if (indexOfLastSpace === -1) {
    	return s;
    }

    return s.substring(0, indexOfLastSpace);
}


let str = "javascript php vb typescript node.js";

str = removeLastWord(str);
 
console.log(str);
  
     
      
      
/*
run:
      
javascript php vb typescript
      
*/

 



answered Feb 15, 2022 by avibootz
edited Feb 15, 2022 by avibootz
0 votes
function removeLastWord(s) {
  // Trim trailing spaces
  s = s.trimEnd();

  const indexOfLastSpace = s.lastIndexOf(" ");

  if (indexOfLastSpace === -1) {
    return s; // no space → return original
  }

  return s.substring(0, indexOfLastSpace);
}

let s;

s = "c c++ c# java go";
s = removeLastWord(s);
console.log("1. " + s);

s = "";
s = removeLastWord(s);
console.log("2. " + s);

s = "go";
s = removeLastWord(s);
console.log("3. " + s);

s = "c# java go ";
s = removeLastWord(s);
console.log("4. " + s);

s = "  ";
s = removeLastWord(s);
console.log("5. " + s);



/*
run:

1. c c++ c# java
2. 
3. go
4. c# java
5. 

*/

 



answered Mar 27 by avibootz
...