在javascript中找到一个位置的单词

rov*_*sen 7 javascript string

对于'这是一个句子'的字符串输入,当位置为6或7时,它必须返回'is'.当position为0时,1,2,3或4结果必须为'this'.

什么是最简单的方法?

Ple*_*and 17

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);

}
Run Code Online (Sandbox Code Playgroud)

此函数接受任何空白字符作为单词分隔符,包括空格,制表符和换行符.从本质上讲,它看起来:

  • 对于单词的开头,匹配 /\S+$/
  • 刚刚结束这个词,使用 /\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.
Run Code Online (Sandbox Code Playgroud)

修改为返回前一个单词,输出变为:

0: This
1: This
2: This
3: This
4: This
5: is
6: is
7: is
8: a
9: a
10: sentence.
// ...
18: sentence.
Run Code Online (Sandbox Code Playgroud)

  • 我没有得到修改的正则表达式/\S +\s*/的相同结果.见[jsfiddle](http://jsfiddle.net/Zf34H/). (2认同)

t-m*_*art 11

在撰写本文时,我在最受欢迎的答案中有一些奇怪的行为,如果位置位于不是最后一个单词的单词的最后一个字符,则获取该单词。

这是我的演绎:

  • 我没有返回单词,而是返回开始和结束索引以获得更大的灵活性。
  • 我使用正则表达式来检测空格。这提供了不同语言环境下的多功能性,并且仍然相对高效,因为只检查了 1 个字符。
  • 注意:当位置的两边(或字符串的开头/结尾)有空格时,函数返回[position, position]. 这实际上是有道理的,因为该位置没有单词:它是一个长度为 0 的单词。
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];
}
Run Code Online (Sandbox Code Playgroud)

要插入子字符串,只需解构返回的边界。

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

const [start, end] = getWordBoundsAtPosition(myString, position);
const wordAtPosition = myString.substring(start, end); // => 'is'
Run Code Online (Sandbox Code Playgroud)

酷可视化

我创建了此方法返回的边界在下面字符串中的位置的可视化:

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];
}
Run Code Online (Sandbox Code Playgroud)
const myString = 'This is a sentence.';
const position = 7;

const [start, end] = getWordBoundsAtPosition(myString, position);
const wordAtPosition = myString.substring(start, end); // => 'is'
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 1

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));
Run Code Online (Sandbox Code Playgroud)

像这样的东西。一定要彻底测试循环逻辑;我没有。