Javascript 从某个索引值中获取单词

Javascript 从某个索引值中获取单词,javascript,Javascript,比如说,我把字符串“hello world”作为输入字符串 var str = document.getElementById("call_search").value; function find_word() { //code here? } 例如,我想从某个索引中得到一个单词 我想要索引5中的“世界”一词 我该怎么做呢?使用indexOf和slice方法来实现这一点 //you can give the string and the word that you want as a

比如说,我把字符串“hello world”作为输入字符串

var str = document.getElementById("call_search").value;

function find_word() {
//code here?
}
例如,我想从某个索引中得到一个单词 我想要索引5中的“世界”一词


我该怎么做呢?

使用
indexOf
slice
方法来实现这一点

 //you can give the string and the  word that you want as a parameter to your find word function 
    function find_word(str,word) {

      var index=str.indexOf(word); 

     return str.slice(index);
    }

str.slice(beginSlice[,endSlice])


从搜索索引中搜索下一个空白。将字符串从搜索索引分割到单词的空白索引

var str = 'Hello World Everyone';
var searchIndex = 5;
var endOfWord = str.indexOf(" ",searchIndex+1);
var output;
if(endOfWord === -1)
{
    endOfWord = str.length;
}
output = str.slice(searchIndex, endOfWord).trim();
console.log(output);

这不是OP要求的相反吗?当你说“索引5中的单词”时,你是指从索引5到字符串末尾的所有字符,还是从索引到第一个空格或标点字符,还是。。。?如果指定的索引实际上不是单词的开头怎么办?(事实上,“hello world”的索引5是一个空格-注意JS字符串索引值从0开始,而不是1。)如果字符串是hello world会发生什么!!!,本例中的结果将是“世界!!!”,而不是“世界”。这不是正确的答案,国际海事组织。这个解决方案与我的问题相同。如果索引恰好位于单词的中间,它会将单词切碎。
var str = 'Hello World Everyone';
var searchIndex = 5;
var endOfWord = str.indexOf(" ",searchIndex+1);
var output;
if(endOfWord === -1)
{
    endOfWord = str.length;
}
output = str.slice(searchIndex, endOfWord).trim();
console.log(output);