Stack Overflow Asked by maimok on December 3, 2021
I’ve been able to find examples of how to remove the last word of a string, but in this instance I’m attempting to remove the last 3 words of a string. I’ve attempted this by adjusting some of the answers I’ve come across to remove a single word but none have gave me the expected results.
Example string Highest ranked in the states
I would like my return value be Highest ranked
Here are some code snippets of what I’ve attempted:
let myString = "Highest ranked in the states";
myString = myString.substring(2, myString.lastIndexOf(" "));
console.log(myString)
let myString2 = "I want to remove the last word";
let mySplitResult2 = myString2.split(" ");
let lastWord = mySplitResult2[mySplitResult2.length-3]
console.log(lastWord)
with the adjusting the substring method to (2, myString.lastIndexOf(" "));
it ended up removing the first two letters of my sentence and only removed the word states
such as "guest ranked in the"
when adjusting the .split() method to length -3 it simply returns back the word in
instead of in the states
Here's a function that can do that for you. (It can actually remove all characters from the Nth-to-last occurrence of any character you specify, not just the Nth-to-last word.)
In your case:
char
parameter should get the value ' '
(ie spaces between words)N
should get the value 3
(to target the 3rd-to-last space)I added an excludeChar
parameter that you can set to true
to avoid returning the final space (or you can use the .trim
method on the result).
const
myString = "Highest ranked in the states",
result = truncateAtNthToLastOccurencOfChar(myString, ' ', 3);
console.log(result);
function truncateAtNthToLastOccurencOfChar(str, char, N, excludeChar){
// Makes counter, converts str to arr & reverses it
let i = -1, rev = Array.from(str).reverse();
// Increments counter (and executes even when i=0)
while(++i || true){
// Returns original string if at the end `char` has occured fewer than `N` times
if(i >= rev.length - 1){
return str;
}
// If current character matches `char`, decrements `N`
if(rev[i] == char && --N === 0){
// If N=0, `i` is our target, all keeps characters (from reversed array)
// starting at `i` (or after `i` if excludeChar=true)
return rev
// The occurence of char can be excluded from result
.slice(excludeChar ? (i + 1) : i)
.reverse() // Restores original character order
.join(''); // Converts back to string
}
}
}
Answered by Cat on December 3, 2021
Here is a nice and readable one liner:
const remove3words = words => words.split(" ").slice(0, -3).join(" ");
console.log(remove3words("Highest ranked in the states"));
console.log(remove3words("Exactly three words"));
You can generalize it easily to n
words in the following way:
function remove_n_words(words, n) {
return n === 0 ? words : words.split(" ").slice(0, -n).join(" ");
}
// Test the function
console.log(remove_n_words("Highest ranked in the states", 0));
console.log(remove_n_words("Highest ranked in the states", 3));
console.log(remove_n_words("Highest ranked in the states", 100));
Answered by shmulvad on December 3, 2021
let myString = "Highest ranked in the states";
myString = myString.split(' ')
myString = myString.splice(myString.length-5,2)
myString = myString.join(' ')
console.log(myString)
Answered by iKaio on December 3, 2021
See comments for explanation using split and splice
let myString = "Highest ranked in the states";
//split the str using blank space between each word and add to new variable
let str = myString.split(" ");
//get the length
let num = str.length;
//splice the array removing the last three values with the number - 3
let newStr = str.splice(0, num - 3);
let displayText = '';
//back into string
newStr.forEach(function(value){
displayText += value + ' ';
});
display.textContent = displayText;
<div id="display"></div>
Answered by dale landry on December 3, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP