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
...