gpt4 book ai didi

javascript - 使用 jquery 在特定文本前后抓取 50 个字符

转载 作者:行者123 更新时间:2023-11-30 08:25:13 29 4
gpt4 key购买 nike

我需要使用 jquery 获取特定文本前后的 50 个字符。例如:

He has Ashish Nehra, who will retire from all forms of the game shortly, to take inspiration from and Pathan says, “he has been a wonderful warrior. He has done very well to make a comeback at this age and shows anyone can do it. I am not that old and I am working hard and my fitness is very good now.” “I want to improve my fielding but I am not thinking ahead of myself.”

我需要在“warrior”这个词前后各输入 50 个字符。

最佳答案

获取您要查找的单词的索引并考虑其长度,然后获取接下来的 50 个和之前的 50 个字符,并在必要时加入它们:

const input = "He has Ashish Nehra, who will retire from all forms of the game shortly, to take inspiration from and Pathan says, “he has been a wonderful warrior. He has done very well to make a comeback at this age and shows anyone can do it. I am not that old and I am working hard and my fitness is very good now.” “I want to improve my fielding but I am not thinking ahead of myself.”"

let index = input.indexOf("warrior"),
offset = "warrior".length;

let charactersAfter = input.substr(index + offset, 50),
charactersBefore = input.substr(0, index).slice(-50),
joined= charactersAfter + charactersBefore;

console.log(charactersAfter);
console.log(charactersBefore);
console.log(joined);

如果这个词重复出现,预计会出现意想不到的结果或明确要求。

注意:没有使用 jQuery,因为它根本没有必要。


编辑:

使用正则匹配整个单词:

const input = "He has Ashish Nehra, who will retire from all forms of the game shortly, to take inspiration from and Pathan says, “he has been a wonderful warrior. He has done very well to make a comeback at this age and shows anyone can do it. I am not that old and I am working hard and my fitness is very good now.” “I want to improve my fielding but I am not thinking ahead of myself.”"

let index = input.match(/\bwarrior\b/).index,
offset = "warrior".length;

let charactersAfter = input.substr(index + offset, 50),
charactersBefore = input.substr(0, index).slice(-50),
joined= charactersAfter + charactersBefore;

console.log(charactersAfter);
console.log(charactersBefore);
console.log(joined);

关于javascript - 使用 jquery 在特定文本前后抓取 50 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46847127/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com