My Code:
I tried the following code
var str = "Have fun storming the castle!"
var character = "!";
function endsWith(str, character) {
return str.indexOf(character, str.length - character.length) !== -1;
}
alert(endsWith(str, character));
It is giving the result as True since such word is present in the sentence.
But I need the result as castle! as it is the only word having such character atlast. If multiple words having such character also, I need those words.
The function below takes the string and character, and returns an array of words that have the character as their last character. It is case sensitive but if you wanted to make it case insensitive then just add
.toLowerCase()to the comparison line.Outputs
Multiple words test:
Outputs
jsFiddle Demo