finding the word at a position in javascript

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

    var str = "this is a sentence";
    
    function GetWordByPos(str, pos) {
        var left = str.substr(0, pos);
        var right = str.substr(pos);
    
        left = left.replace(/^.+ /g, "");
        right = right.replace(/ .+$/g, "");
    
        return left + right;
    }
    
    alert(GetWordByPos(str, 6));
    

    P.S. Not tested throughly and no error handling yet.

提交回复
热议问题