Word Proximity Search

02/04/2023, Sat
Categories: #JavaScript

When you search for related words in a general area that are not in strict sequential order, you will have to resort to use a regex pattern that search across multiple words at a time.

"firstword someword anotherword someotherword secondword".match(/\b(?:firstword(?:\W+\w+){1,3}?\W+secondword)\b/g)

// Returns
// ["firstword someword anotherword someotherword secondword"]

This will only look at the actual word distance, and this will match across sentences. The above example will match the separated words if there are three or fewer words between them and will fail to match if greater than four words between them. This will return the whole string as the result.

If there is a need to match the words in the reverse order, add the second regex pattern branch with the words in the flipped locations.

"secondword someword anotherword someotherword firstword".match(/\b(?:firstword(?:\W+\w+){1,3}?\W+secondword|secondword(?:\W+\w+){1,3}?\W+firstword)\b/g)

To use this in the VSCode code editor, use this regex pattern

(?:firstword(?:\W+\w+){1,3}?\W+secondword|secondword(?:\W+\w+){1,3}?\W+firstword)