xxxxxxxxxx
// Get the last word of a string.
let str = "What I hate most in the world is fanaticism.";
// 1) The slice() method: without Considering the punctuation marks
str.slice(str.lastIndexOf(' ')); // => 'fanaticism.'
// 2) the spit() method():
let arr = str.split(' ');
arr[arr.length - 1]; // => 'fanaticism.'
// Considering the punctuation marks at the end of the string
str.match(/\b(\w+)\W*$/)[1]; // => 'fanaticism'
xxxxxxxxxx
// Method 1: Using string indexing
str[str.length-1];
// Method 2: Using charAt()
str.charAt(str.length-1)
// Method 3: Using str.slice() function
str.slice(-1);
// Method 4: Using str.substr()
str.substr(-1);
xxxxxxxxxx
var str = "Hello";
var newString = str.substring(0, str.length - 1); //newString = Hell
xxxxxxxxxx
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
xxxxxxxxxx
function test(words) {
var n = words.split(" ");
return n[n.length - 1];
}
xxxxxxxxxx
// To get the last "Word" of a string use the following code :
let string = 'I am a string'
let splitString = string.split(' ')
let lastWord = splitString[splitString.length - 1]
console.log(lastWord)
/*
Explanation : Here we just split the string whenever there is a space and we get an array. After that we simply use .length -1 to get the last word contained in that array that is also the last word of the string.
*/
xxxxxxxxxx
// Get last n characters from string
var name = 'Shareek';
var new_str = name.substr(-5); // new_str = 'areek'