Search word in position in javascript

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

What is the easiest way?

+7
source share
6 answers
function getWordAt (str, pos) {

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

    // Search for the word 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 space character as a word separator, including spaces, tabs, and newlines. Essentially, this looks like:

  • To start a word corresponding /\S+$/
  • Ending the word using /\s/

, "", ; . , , /\S+$/ /\S+\s*/.


"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.

, :

0: This
1: This
2: This
3: This
4: This
5: is
6: is
7: is
8: a
9: a
10: sentence.
// ...
18: sentence.
+17
var str = "this is a sentence";

function GetWordByPos(str, pos) {
    var left = str.substr(0, pos);
    var right = str.substr(pos);

    left = left.replace(/^.+ /g, "");
    right = right.replace(/ .+$/g, "");

    return left + right;
}

alert(GetWordByPos(str, 6));

P.S. .

+3
function getWordAt(str, pos) {

   // Sanitise input
   str = str + "";
   pos = parseInt(pos, 10);

   // Snap to a word on the left
   if (str[pos] == " ") {
      pos = pos - 1;
   }

   // Handle exceptional cases
   if (pos < 0 || pos >= str.length-1 || str[pos] == " ") {
      return "";
   }

   // Build word
   var acc = "";
   for ( ; pos > 0 && str[pos-1] != " "; pos--) {}
   for ( ; pos < str.length && str[pos] != " "; pos++) {
      acc += str[pos];
   }

   return acc;
}

alert(getWordAt("this is a sentence", 6));

- . ; .

+1
function getWordAt(s, pos) {
  // make pos point to a character of the word
  while (s[pos] == " ") pos--;
  // find the space before that word
  // (add 1 to be at the begining of that word)
  // (note that it works even if there is no space before that word)
  pos = s.lastIndexOf(" ", pos) + 1;
  // find the end of the word
  var end = s.indexOf(" ", pos);
  if (end == -1) end = s.length; // set to length if it was the last word
  // return the result
  return s.substring(pos, end);
}
getWordAt("this is a sentence", 4);
+1

.

1: .

2: ( ) , ( pos) .

function getWordByPosition(str, pos) {
  let leftSideString = str.substr(0, pos);
  let rightSideString = str.substr(pos);

  let leftMatch = leftSideString.match(/[^.,\s]*$/);
  let rightMatch = rightSideString.match(/^[^.,\s]*/);

  let resultStr = '';

  if (leftMatch) {
      resultStr += leftMatch[0];
  }

  if (rightMatch) {
      resultStr += rightMatch[0];
  }

  return {
      index: leftMatch.index,
      word: resultStr
  };
}
0

, , .

:

  • , , .
  • , , , 1 .
  • . position position-1 , [position, position]. , .
function getWordBoundsAtPosition(str, position) {
  const isSpace = (c) => /\s/.exec(c);
  let start = position - 1;
  let end = position;

  while (start >= 0 && !isSpace(str[start])) {
    start -= 1;
  }
  start = Math.max(0, start + 1);

  while (end < str.length && !isSpace(str[end])) {
    end += 1;
  }
  end = Math.max(start, end);

  return [start, end];
}

, .

const myString = 'This is a sentence.';
const position = 7;

const wordBoundsAtPosition = getWordBoundsAtPosition(myString, position);
const wordAtPosition = myString.substring(...wordBoundsAtPosition); // => 'is'

Cool visualization

I created a visualization of where the borders returned by this method are in your line below:

function getWordBoundsAtPosition(str, position) {
  const isSpace = (c) => /\s/.exec(c);
  let start = position - 1;
  let end = position;

  while (start >= 0 && !isSpace(str[start])) {
    start -= 1;
  }
  start = Math.max(0, start + 1);

  while (end < str.length && !isSpace(str[end])) {
    end += 1;
  }
  end = Math.max(start, end);
  
  return [start, end];
}

function analyzeStringWithCursor(str, bounds, cursorIdx) {
  document.getElementById("analysis").innerText = '
 ${"0123456789".repeat(Math.floor((str.length - 1) / 10) + 1)}
 ${str}
${" ".repeat(bounds[0])}↗${" ".repeat(bounds[1] - bounds[0])}↖
Cursor: ${cursorIdx}
getWordBoundsAtPosition("${str}", ${cursorIdx}): ${JSON.stringify(bounds)}
substring(${bounds[0]}, ${bounds[1]}): "${str.substring(...bounds)}"
';
}

document.getElementById("input").onkeyup = e => {
  analyzeStringWithCursor(
    e.target.value,
    getWordBoundsAtPosition(e.target.value, e.target.selectionStart),
    e.target.selectionStart
  );
};
<p>Type some words below. The cursor (moved by typing or arrow keys) 
indicates the current position.</p>
<input id="input" type="search" placeholder="Start typing some words..." />
<pre id="analysis"></pre>
Run codeHide result

0
source

Source: https://habr.com/ru/post/1795856/


All Articles