在javascript中的某个位置找到单词 [英] finding the word at a position in javascript

查看:48
本文介绍了在javascript中的某个位置找到单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于'this is a sentence'的字符串输入,当位置为6或7时必须返回'is'.当位置为0、1、2、3或4时,结果必须为'this'.

最简单的方法是什么?

解决方案

function getWordAt (str, pos) {//执行类型转换.str = String(str);pos = Number(pos) >>>0;//搜索单词的开头和结尾.var left = str.slice(0, pos + 1).search(/\S+$/),right = str.slice(pos).search(/\s/);//字符串中的最后一个单词是一个特例.如果(右 <0){返回 str.slice(left);}//返回单词,使用定位的边界从字符串中提取它.返回 str.slice(left, right + pos);}

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

  • 为单词的开头,匹配/\S+$/
  • 刚过词尾,使用/\s/

如所写,如果给出空白字符的索引,该函数将返回"";空格不是单词本身的一部分.如果您希望函数改为返回前面的单词,请将 /\S+$/ 更改为 /\S+\s*/.<小时>

这是This is a sentence."的一些示例输出.

0: 这个1:这个2:这个3:这个4:5:是6:是7:8:一个9:10:句子.//...18:句子.

<小时>

修改为返回前面的单词,输出变为:

0: 这个1:这个2:这个3:这个4:这个5:是6:是7:是8:一个9:一个10:句子.//...18:句子.

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?

解决方案

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.

这篇关于在javascript中的某个位置找到单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆