簡體   English   中英

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

[英]How to extract string from starting index to white space character using javascript?

我是編程新手,想從某個索引中提取一個字符串,直到一個空白字符。

考慮字符串"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 from user"; var cursorPosition = 6; str = str.substr(cursorPosition, str.length).substr(0, str.indexOf(' ')); console.log(str); 

您可以使用.slice()將字符串從起始索引切到單詞的末尾,然后對新字符串使用.split()將其“分塊”成一個數組,其中每個元素都是一個單詞,與字符串,以空格分隔。

例如:

"hello world from user" --> slice(6) --> "world from user"

然后:

"world from user" --> split(' ') --> ["world", "from", "user"]

從分割數組中獲取第一個元素/單詞(索引0 )將得到"word"

請參見下面的示例:

 const str = "hello world from user"; const idx = 6; const res = str.slice(idx).trim().split(' ')[0]; console.log(res); // "world" 

如果需要它,那么當從空格開始時會得到下一個單詞,可以在數組.split()之前使用.trim()

 const str = "hello world from user"; const idx = 5; const res = str.slice(idx).trim().split(' ')[0]; console.log(res); // "world" 

你可以這樣實現

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)

indexOffromIndex作為第二個參數。 因此,不需要所有這些鏈接。 您可以簡單地使用下面的功能。

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM