finding the word at a position in javascript

前端 未结 6 2065
慢半拍i
慢半拍i 2020-12-10 06:18

For string input of \'this is a sentence\' it must return \'is\' when position is 6 or 7. When position is 0, 1, 2, 3 or 4 result must be \'this\'.

What is the easie

6条回答
  •  [愿得一人]
    2020-12-10 07:05

    function getWordAt(str, pos) {
    
       // Sanitise input
       str = str + "";
       pos = parseInt(pos, 10);
    
       // Snap to a word on the left
       if (str[pos] == " ") {
          pos = pos - 1;
       }
    
       // Handle exceptional cases
       if (pos < 0 || pos >= str.length-1 || str[pos] == " ") {
          return "";
       }
    
       // Build word
       var acc = "";
       for ( ; pos > 0 && str[pos-1] != " "; pos--) {}
       for ( ; pos < str.length && str[pos] != " "; pos++) {
          acc += str[pos];
       }
    
       return acc;
    }
    
    alert(getWordAt("this is a sentence", 6));
    

    Something like this. Be sure to thoroughly test the loop logic; I didn't.

提交回复
热议问题