The simplest way to get remove the last word from a string is in JavaScript Using string.substring() Function. There are many ways and methods. We will see the other method with examples in this tutorial.
JavaScript remove the last word from a string Example
HTML example code:-
Using substring() Function
The lastIndexOf() function is used to get the last index of the specific character in the string. And the substring() function is used to extract the characters from a string, between two specified indices, and returns the new substring.
<!DOCTYPE HTML>
<html>
<body>
<script>
var str = "Remove the last word.";
var index = str.lastIndexOf(" ");
str = str.substring(0, index);
console.log(str)
</script>
</body>
</html>
split(), pop() and join() Function
Use the split() function to split the string into the array, the array pop() function is used to remove the last element of an array and returns that element. User the array join() function returns the array as a string.
<script>
var str = "Remove the last word.";
var res = str.split(" ");
res.pop();
console.log(res.join(" "));
</script>
Another split(), splice() and join() Function
User the split() function to split the string into words and the splice() function removes items from an array and returns the removed item(s) and the join() function returns the array as a string.
<script>
var str = "Remove the last word.";
var newStr = str.split(" ").slice(0, -1).join(" ");
console.log(newStr)
</script>
Output: The result string will be the same for all examples because the input string is the same.
Do comment if you have any doubts and suggestions on this JS String topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version