How To Remove The Last 2 Words From A String In JavaScript

Remove the Last 2 Words from a String in JavaScript

Welcome back to the Javascript lesson series. Today I will show you how to remove the last 2 words from a string in JavaScript using the loop and slice() method. Please read the below article to complete it.

Remove the last 2 words from a string in JavaScript

Use for loop

For loop is an indispensable tool in any programming language. Javascript is no exception. Not only that, but it also has stronger support.

To remove the last two words from a string in JavaScript using for loop, you must understand how for loop loops through each element. The following example will show you:

// Init original string
var str = 'Hello guys, welcome to LearnShare IT!!';

// A new string
var str1 = '';

// An array of indexes space
var contains = [];

// The index next to the end
var space;

// Get indexes space
for (let i = 0; i < str.length; i++) {
	if (str[i] === ' ') {
		contains.push(i);
	}
}

// Get the index next to the end
space = contains[contains.length - 2];

// Get a new string
for (let i = 0; i < space; i++) {
	str1 = str1 + str[i];
}

console.log('The index next to the end is: ' + space);
console.log('The array of indexes space is: ' + contains);
console.log('The result is:\n' + str1);

Output

The index next to the end is: 22
The array of indexes space is: 5,11,19,22,33
The result is:
Hello guys, welcome to

I will explain a bit about the above code.

  • Firstly, I declare variables including an original string str, a new string with the last 2 words truncated from the original string str1.
  • Then an array of space values ​​and to remove the last 2 words of the string, I need a variable containing the space value near the end. The algorithm is very simple. With the first for loop, I can get the position of space values ​​and assign it to contains with the if statement and push() method.
  • After I get all the values, ​​I will get the space value near the end equal to the length of the array minus 1.
  • And finally, with the second for loop, I add each element of the original string together until the space variable is reached.

For this algorithm, you can truncate any string element based on the space variable you take.

It is very flexible in many cases, and you should try it before moving on to the next option.

Combine 3 methods split(), slice(), and join()

To understand this example, you need to know the syntax, and working principle of split(), slice(), and join(). Each of these methods I have presented in previous lessons. Please review to understand better.

Below I will show an example and how it works so, you can apply those methods dynamically.

// Init myStr
const myStr = 'hello, my name is Edward!!';

// Remove last two words
const result = myStr.split(' ').slice(0, -2).join(' ');

// Show the result
console.log('After remove last two word:\n' + result);

Output

After remove last two word:
hello, my name

The code is straightforward and concise.

  • First, use the split() method to split each word and put it in the array.
  • Then use the slice() method to slice the last 2 elements of that array.
  • Finally, use the join() method to combine all the remaining elements in the array, separated by ' '.

To see the result of each stage, you can separate the methods and do them one by one.

Summary

In the above article, I showed you two ways to remove the last 2 words from a string in JavaScript, which are the best ways for your project. You can refer to the substring() method and combine it with other methods. It can be useful. Thanks for reading.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *