Posted By

jatkins on 03/13/16


Tagged

words String strings word


Versions (?)

Get last word of a string


 / Published in: JavaScript
 

2016

  1. function lastWord (str) {
  2. var lastWordStart, lastWordEnd,
  3. curPos = str.length - 1,
  4. NBSP = String.fromCharCode(160);
  5.  
  6. str = str.replace(/\s/g, NBSP);
  7.  
  8. while (curPos >= 0 && str.charAt(curPos) === NBSP) {
  9. curPos--;
  10. }
  11. lastWordEnd = curPos + 1;
  12.  
  13. while (curPos >= 0 && str.charAt(curPos) !== NBSP) {
  14. curPos--;
  15. }
  16. lastWordStart = curPos + 1;
  17.  
  18. return {
  19. word: str.substring(lastWordStart, lastWordEnd),
  20. start: lastWordStart,
  21. end: lastWordEnd
  22. };
  23. }

Report this snippet  

You need to login to post a comment.