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

时间:2011-03-02 20:54:21

标签: javascript string

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

最简单的方法是什么?

6 个答案:

答案 0 :(得分:15)

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

}

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

  • 单词的开头,与/\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.

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

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

答案 1 :(得分:3)

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。没有彻底测试,也没有错误处理。

答案 2 :(得分: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));

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

答案 3 :(得分: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);

答案 4 :(得分:0)

我最终找到了自己的解决方案。

注意1:正则表达式未经过全面测试。

注2:此解决方案速度很快(即使对于大字符串也是如此),即使位置(isLife(a)参数位于单词的中间)也可以使用。

pos

答案 5 :(得分:0)

我在the most popular answer at time of writing中有一些奇怪的行为,即如果该位置位于不是最后一个单词的单词的最后一个字符处,则会得到该单词。

这是我的作品:

  • 我返回单词边界的索引,而不是返回单词,以提高灵活性。
  • 我使用正则表达式来检测空白,因为空白列表很大,在不同的语言环境下会有所不同,并且由于只检查了1个字符而仍然表现良好。
  • 注意:当positionposition-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'

酷视觉

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

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>