Last word using JavaScript

Last word using JavaScript and avoiding multiple spaces

by aburayane

HTML

<textarea name="recepients" id="recepients" onkeyup="myFunction()"></textarea>

JavaScript

function myFunction(){

var contents = document.getElementById("recepients").value;
console.log('cont '+contents);

// replace more than one space
var contents = contents.replace(/ +(?= )/g,'');

var contentsSpl = contents.split(' ');
console.log('spl '+contentsSpl);

var indexKey = contentsSpl.length;
console.log('index '+indexKey);

var lastWord = contentsSpl[indexKey - 1];

// if last word is a space ' ' (blank)
if(lastWord == ''){
// change the indexKey to -2
var show = contentsSpl[indexKey - 2];
} else {
// show last word with indexKey -1
var show = lastWord;
}

alert(show);
} // end function