Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the word at a position in javascript

For string input of 'this is a sentence' it must return 'is' when position is 6 or 7. When position is 0, 1, 2, 3 or 4 result must be 'this'.

What is the easiest way?

like image 366
rovsen Avatar asked Mar 02 '11 20:03

rovsen


People also ask

How do I search for a specific word in Javascript?

The search() method returns the index (position) of the first match. The search() method returns -1 if no match is found. The search() method is case sensitive.

How do you find position string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

What is the use of indexOf () method in Javascript?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

What is lastIndexOf in Javascript?

lastIndexOf() The lastIndexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring.


1 Answers

function getWordAt (str, pos) {

    // Perform type conversions.
    str = String(str);
    pos = Number(pos) >>> 0;

    // Search for the word's beginning and end.
    var left = str.slice(0, pos + 1).search(/\S+$/),
        right = str.slice(pos).search(/\s/);

    // The last word in the string is a special case.
    if (right < 0) {
        return str.slice(left);
    }

    // Return the word, using the located bounds to extract it from the string.
    return str.slice(left, right + pos);

}

This function accepts any whitespace character as a word separator, including spaces, tabs, and newlines. Essentially, it looks:

  • For the beginning of the word, matched by /\S+$/
  • Just past the end of the word, using /\s/

As written, the function will return "" if the index of a whitespace character is given; spaces are not part of words themselves. If you want the function to instead return the preceding word, change /\S+$/ to /\S+\s*/.


Here is some example output for "This is a sentence."

0: This
1: This
2: This
3: This
4:
5: is
6: is
7:
8: a
9:
10: sentence.
// ...
18: sentence.

Modified to return the preceding word, the output becomes:

0: This
1: This
2: This
3: This
4: This
5: is
6: is
7: is
8: a
9: a
10: sentence.
// ...
18: sentence.
like image 170
PleaseStand Avatar answered Oct 21 '22 18:10

PleaseStand