什么';获取JavaScript字符串数组中相邻字符的最佳方法是什么?
假设我有这个:什么';获取JavaScript字符串数组中相邻字符的最佳方法是什么?,javascript,arrays,string,Javascript,Arrays,String,假设我有这个: var arr=[“在动物园探险时,我们看到每只袋鼠都在跳,还有不少袋鼠抱着婴儿。”,“巫师在侏儒们蒸发之前很快地给他们施了咒。”,“敏捷的棕色狐狸跳过了懒狗。” 我试图找出一种方法,当我输入“厄运”时,我也会得到“快速向导”和“之前的侏儒”。不一定是整个单词,我只想在输入的前后两个字符中找到几个字符。我一直在这方面碰壁,所以我很感激任何建议和提示 谢谢 使用split获取前面和后面的内容jinxed,然后使用substr获取每个部分的最后或第一个字符: var a = "The
var arr=[“在动物园探险时,我们看到每只袋鼠都在跳,还有不少袋鼠抱着婴儿。”,“巫师在侏儒们蒸发之前很快地给他们施了咒。”,“敏捷的棕色狐狸跳过了懒狗。”代码>
我试图找出一种方法,当我输入“厄运”时,我也会得到“快速向导”和“之前的侏儒”。不一定是整个单词,我只想在输入的前后两个字符中找到几个字符。我一直在这方面碰壁,所以我很感激任何建议和提示
谢谢 使用split
获取前面和后面的内容jinxed
,然后使用substr
获取每个部分的最后或第一个字符:
var a = "The wizard quickly jinxed the gnomes before they vaporized";
var s = a.split('jinxed');
s == [ 'The wizard quickly ',' the gnomes before they vaporized' ]
s[0].substr(-10,10) == 'd quickly '
s[1].substr(0,10) == ' the gnome'
您可以使用正则表达式匹配:
函数搜索(s、q、msg){
//匹配前后的字符
var m=s.match(新的RegExp(“(.|^)”+q+”(.|$)”);
控制台日志(m);
//如果真的有一场比赛,那么就放弃第一场(这就是整场比赛:“倒霉”)
如果(m){
如果(m.length>1){m=m.splice(1)}
//m[0]在前面的字符中,m[1]是后面的字符
警报(msg+“'+m[0]+”、“+m[1]+”);
}否则{
警报(消息+“未找到”);
}
}
搜索(“巫师在侏儒蒸发之前很快给他们施了魔法。”,“施了魔法”,“在中间”);
搜索(“在侏儒蒸发之前诅咒他们。”,“诅咒”,“在开始时”);
搜索(“向导很快就倒霉了”,“倒霉了”,“最后”);
搜索(“不吉利”、“不吉利”、“完整”);
搜索(“快速向导”、“倒霉”、“不在字符串中”)代码>因此,如果输入是“不吉利的”,您希望返回:{charBefore:,charAfter:}?那些空间?
function scan(arr, w) {
// This function is a first attempt to solve your specific problem.
// It just looks for the first occurence of w, the word you are looking for
// It does not cover edge or specific cases, neither is optimized.
// With more specifications, it can be generalized.
// Hope it can help.
var
// utils
regWord = /\w+/g,
wordsBefore, wordsAfter,
matchWord,
found = false;
// loop through your array
arr.forEach(function(item) {
if (found) {
// if we have already found the word, skip the iteration
return false;
}
// clear the arrays of words before and after
wordsBefore = [];
wordsAfter = [];
// strip the words from the array item
// every match is an iterable object containing the word, its index, and the item string
while (match = regWord.exec(item)) {
// get the matched word
matchWord = match[0].toLowerCase();
// if we have found the word we are looking for
if (matchWord === w.toLowerCase()) {
// flag it
found = true;
} else {
// it is not a match, but a word that could be returned in the array before or after
if (!found) {
// if we have not found the word yet
// populate the array of words before
wordsBefore.push(matchWord);
} else {
// otherwise, if we are here, it means that we are in a sentence containing
// the word we are looking for, and we have already found it
// populate the array of words after
wordsAfter.push(matchWord);
}
}
}
});
// return an object containing
return {
// the words before
wordsBefore: wordsBefore,
// the words after
wordsAfter: wordsAfter
}
}