finding the word at a position in javascript

前端 未结 6 2069
慢半拍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:01

    function getWordAt(s, pos) {
      // make pos point to a character of the word
      while (s[pos] == " ") pos--;
      // find the space before that word
      // (add 1 to be at the begining of that word)
      // (note that it works even if there is no space before that word)
      pos = s.lastIndexOf(" ", pos) + 1;
      // find the end of the word
      var end = s.indexOf(" ", pos);
      if (end == -1) end = s.length; // set to length if it was the last word
      // return the result
      return s.substring(pos, end);
    }
    getWordAt("this is a sentence", 4);
    

提交回复
热议问题