从某个索引值中抓取一个单词

时间:2013-12-30 14:01:33

标签: javascript

比方说,我将字符串“hello world”作为输入字符串,

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

function find_word() {
//code here?
}
例如,我希望从某个索引中获取一个单词 我希望索引5中的单词是“世界”。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

使用indexOfslice方法来实现此目标

 //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);
    }

答案 1 :(得分:0)

var str = 'Hello World';

str.slice(5); // " World"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

  

str.slice(beginSlice [,endSlice])

答案 2 :(得分:0)

从搜索索引中搜索下一个空白区域。将字符串从搜索索引切换到空格索引到单词。

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);
相关问题