How to remove the last word from a string in JavaScript

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 c typescript node.js";
 
str = removeLastWord(str);
  
console.log(str);

       
       
/*
run:
       
javascript php c typescript
       
*/

 



answered Feb 15, 2022 by avibootz
edited Mar 27 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 python";
s = removeLastWord(s);
console.log("1. " + s);

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

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

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

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


       
/*
run:
       
1. c c++ c# java
2. 
3. c
4. c# java
5.
       
*/

 



answered Mar 27 by avibootz
...