How would I make jJvascript/jQuery evaluate the last word entered?
Example (doe ra fa la si do) Only evaluate do
Very similar to Google's search box. I want only to evaluate after a space and have that word searched for with an Ajax call.
Here's the code I tried:
$(document).ready(function() {
ajaxcall();
var x = setInterval(ajaxcall, 1000);
function ajaxcall() {
var nameid = $('#word').val();
if (nameid.match(/^\s*$/)) {
// nothing, or nothing but whitespace
} else {
$.get('mysqlquery.php?id=' + nameid, function(data) {
$('#loadbox').append(data + ' ');
});
}
}
});
$(document).ready(function(){
ajaxcall();
var x = setInterval(ajaxcall,1000);
function ajaxcall(){
var nameid = $('#word').val().split(' ');
nameid = nameid[nameid.length-1];
if (nameid.match(/^\s*$/)) {
// nothing, or nothing but whitespace
} else {
$.get('mysqlquery.php?id='+nameid, function(data){
$('#loadbox').append(data+' ');
});
}
}
});
This should return the last word of the string:
var str = 'doe ra fa la si do',
patt = /[^\s]*$/;
alert(str.match(patt)); // Returns `do`
Try using .split()
to convert the string into an array and then using .pop()
to return the last element in the array:
function lastWord(subject)
{
var ar = subject.split(" ");
return ar.pop();
}
lastWord("some amazing sentence"); // sentence