Searching For A Last Word In Javascript
I am doing some logic for the last word that is on the sentence. Words are separated by either space or with a '-' character. What is easiest way to get it? Edit I could do it by t
Solution 1:
Try splitting on a regex that matches spaces or hyphens and taking the last element:
var lastWord = function(o) {
return (""+o).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lastWord('This is a test.'); // => 'test.'lastWord('Here is something to-do.'); // => 'do.'
As @alex points out, it's worth trimming any trailing whitespace or hyphens. Ensuring the argument is a string is a good idea too.
Solution 2:
Solution 3:
Have you tried the lastIndexOf function http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
Or Split function http://www.w3schools.com/jsref/jsref_split.asp
Solution 4:
Here is a similar discussion have a look
Solution 5:
You can try something like this...
<scripttype="text/javascript">var txt = "This is the sample sentence";
spl = txt.split(" ");
for(i = 0; i < spl.length; i++){
document.write("<br /> Element " + i + " = " + spl[i]);
}
</script>
Post a Comment for "Searching For A Last Word In Javascript"