検索する単語とその単語を検索する文字列の両方を渡すことができる機能的なアプローチを使用する次のアプローチをお勧めします。
function findWordAndNeighbours(needle, haystack) {
if (!needle || !haystack) {
return false;
}
else {
var re = new RegExp('(\\S+[\\b\\s]' + needle + '[\\b\\s]\\S+)', 'i'),
foundWords = haystack.match(re)[0].split(/\s+/),
foundFragment = foundWords.join(' ');
return foundFragment;
}
}
var sentenceFragment = findWordAndNeighbours('test', 'This is a Test of a matching thing.');
console.log(sentenceFragment);
JS フィドルのデモ。
上記を更新して、いくつかのエラーキャッチを含めるように編集し、基本的に、それらの一致を処理する前にいくつかの正規表現の一致があることを確認します。
function findWordAndNeighbours(needle, haystack) {
if (!needle || !haystack) {
return false;
}
else {
var re = new RegExp('(\\S+[\\b\\s]' + needle + '[\\b\\s]\\S+)', 'i'),
matches = haystack.match(re);
if (matches) {
// this is for if you wanted the individual words (as an array)
var foundWords = haystack.match(re)[0].split(/\s+/),
// this is to return the found sentence-fragment:
foundFragment = foundWords.join(' ');
return foundFragment;
}
else {
/* this just follows the indexOf() pattern of, if you'd rather
'return false' instead, that's entirely your call. */
return -1;
}
}
}
var sentenceFragment = findWordAndNeighbours('test', 'This is a Test of a matching thing.');
console.log(sentenceFragment);
JS フィドルのデモ。
コメントでOPによって特定された問題を修正するために編集されました(以下):
ただし、This または Thing を検索するとこれは機能しないため、最初または最後の単語を
?
オペランド/特殊文字 (前の文字/グループを 0 回または 1 回一致させることを意味する) を使用すると、指定された文字列の最初と最後の単語を検索する際の問題が修正されるようです。
function findWordAndNeighbours(needle, haystack) {
if (!needle || !haystack) {
return false;
}
else {
var re = new RegExp('((\\S+[\\b\\s]?)' + needle + '([\\b\\s]?\\S+))', 'i'),
matches = haystack.match(re);
console.log(matches);
if (matches) {
var foundWords = haystack.match(re)[0].split(/\s+/),
foundFragment = foundWords.join(' ');
return foundFragment;
}
else {
return -1;
}
}
}
var sentenceFragment = findWordAndNeighbours('es', 'This is a Test of a matching thing.');
console.log(sentenceFragment);
ただし、特定の単語から部分文字列を検索する適切な方法を見つけることができませんでした。たとえば、es
(例のように from test
)。関数は完全な単語を返します (この場合はtest
)。その動作を簡単に修正したい場合は、簡単にif (needle == matches[0]) {/* do something */}
チェックを追加して、最適と思われる動作を変更できます。しかし、それを処理する最善の方法が何であるかは完全にはわかりません。
参考文献: