对于'这是一个句子'的字符串输入,当位置为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)
t-m*_*art 11
在撰写本文时,我在最受欢迎的答案中有一些奇怪的行为,如果位置位于不是最后一个单词的单词的最后一个字符,则获取该单词。
这是我的演绎:
[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)
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)
像这样的东西。一定要彻底测试循环逻辑;我没有。
| 归档时间: |
|
| 查看次数: |
7069 次 |
| 最近记录: |