简体   繁体   中英

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

I'm new to programming and would like to extract a string from certain an index up to a whitespace character.

Consider string "hello world from user"

and the cursor position is at index 6 . From index 6, I want to extract string the string up until the whitespace character so the output would be "world" . How can I achieve this?

I have tried using:

cursor_position = event.target.selectionStart;
extracted_string = event.target.value.substr(cursor_position, 
event.target.value.indexOf(' '));

But this second position for extracting string doesn't seem to be correct. Could someone help me with extracting the string from the cursor's position to the white space character?

Thanks.

First you need to get the string from the cursor position to the end of the string. Afterwards you can chain another .substr() call to trim the string from the beginning to the first occurence of a whitespace. Here's an example:

 var str = "hello world from user"; var cursorPosition = 6; str = str.substr(cursorPosition, str.length).substr(0, str.indexOf(' ')); console.log(str); 

You can use .slice() to cut the string from your starting index to the end of the word, and then use .split() on your new string to "chunk" it into an array where each element is a word separated from the string separated by a space.

Eg:

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

Then:

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

Getting the first element/word (index 0 ) from the split array will give "word"

See example below:

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

If you need it such that when you start on a space you get the next word, you can use .trim() before you .split() the array:

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

You can achieve it this way

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 takes fromIndex as a second argument. So no need to have all those chainings. You can simply use the function below.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM