如何使用javascript将字符串从起始索引提取到空白字符?

如何使用javascript将字符串从起始索引提取到空白字符?,javascript,Javascript,我是编程新手,希望从某个索引中提取一个字符串,直到一个空白字符 考虑字符串“hello world from user” 光标位置在索引6处。从索引6中,我想提取字符串直到空格字符,这样输出将是“world”。我怎样才能做到这一点 我试过使用: cursor_position = event.target.selectionStart; extracted_string = event.target.value.substr(cursor_position, event.target.valu

我是编程新手,希望从某个索引中提取一个字符串,直到一个空白字符

考虑字符串“hello world from user”

光标位置在索引
6
处。从索引6中,我想提取字符串直到空格字符,这样输出将是
“world”
。我怎样才能做到这一点

我试过使用:

cursor_position = event.target.selectionStart;
extracted_string = event.target.value.substr(cursor_position, 
event.target.value.indexOf(' '));
但提取字符串的第二个位置似乎不正确。有人能帮我把字符串从光标位置提取到空白字符吗


谢谢。

首先,您需要获取从光标位置到字符串末尾的字符串。 之后,您可以链接另一个.substr()调用,将字符串从开头修剪到第一次出现空白。 下面是一个例子:

var str=“来自用户的hello world”;
var cursorPosition=6;
str=str.substr(光标位置,str.length).substr(0,str.indexOf(“”));

console.log(str)首先,您需要获取从光标位置到字符串末尾的字符串。 之后,您可以链接另一个.substr()调用,将字符串从开头修剪到第一次出现空白。 下面是一个例子:

var str=“来自用户的hello world”;
var cursorPosition=6;
str=str.substr(光标位置,str.length).substr(0,str.indexOf(“”));
console.log(str)您可以使用将字符串从起始索引剪切到单词的结尾,然后在新字符串上使用将其“分块”到一个数组中,其中每个元素都是一个单词,与用空格分隔的字符串分开

例如:

然后:

"world from user" --> split(' ') --> ["world", "from", "user"]
从拆分数组中获取第一个元素/单词(索引
0
)将给出
“单词”

见下例:

const str=“来自用户的hello world”;
常数idx=6;
const res=str.slice(idx).trim().split(“”)[0];
console.log(res);//“world”
您可以使用将字符串从起始索引剪切到单词的结尾,然后在新字符串上使用“chunk”将其“chunk”到一个数组中,其中每个元素都是一个单词,由空格分隔

例如:

然后:

"world from user" --> split(' ') --> ["world", "from", "user"]
从拆分数组中获取第一个元素/单词(索引
0
)将给出
“单词”

见下例:

const str=“来自用户的hello world”;
常数idx=6;
const res=str.slice(idx).trim().split(“”)[0];

console.log(res);//“世界”
你可以通过这种方式实现它

cursor_position = event.target.selectionStart;
extracted_string = event.target.value.substr(cursor_position);
next_word_length = extracted_string.split(' ')[0].length
next_word = event.target.value.substr(cursor_position, next_word_length)

你可以这样做

cursor_position = event.target.selectionStart;
extracted_string = event.target.value.substr(cursor_position);
next_word_length = extracted_string.split(' ')[0].length
next_word = event.target.value.substr(cursor_position, next_word_length)

indexOf
fromIndex
作为第二个参数。所以不需要所有的链子。您可以简单地使用下面的函数

const extract = (str, startIndex, search = " ") => str.slice(startIndex, str.indexOf(search, startIndex));

const myString = extract("hello world from user", 6);
console.log(myString);

// Output: "world"

indexOf
fromIndex
作为第二个参数。所以不需要所有的链子。您可以简单地使用下面的函数

const extract = (str, startIndex, search = " ") => str.slice(startIndex, str.indexOf(search, startIndex));

const myString = extract("hello world from user", 6);
console.log(myString);

// Output: "world"

event.target.value.substr(str.indexOf(“world”)).split(“”)[0]
event.target.value.substr(str.indexOf(“world”)).split(“”)[0]