match-query.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import get from 'lodash.get'
  2. export default (query, page, additionalStr = null) => {
  3. let domain = get(page, 'title', '')
  4. if (get(page, 'frontmatter.tags')) {
  5. domain += ` ${page.frontmatter.tags.join(' ')}`
  6. }
  7. if (additionalStr) {
  8. domain += ` ${additionalStr}`
  9. }
  10. return matchTest(query, domain)
  11. }
  12. const matchTest = (query, domain) => {
  13. const escapeRegExp = (str) => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
  14. // eslint-disable-next-line no-control-regex
  15. const nonASCIIRegExp = new RegExp('[^\x00-\x7F]')
  16. const words = query
  17. .split(/\s+/g)
  18. .map((str) => str.trim())
  19. .filter((str) => !!str)
  20. if (!nonASCIIRegExp.test(query)) {
  21. // if the query only has ASCII chars, treat as English
  22. const hasTrailingSpace = query.endsWith(' ')
  23. const searchRegex = new RegExp(
  24. words
  25. .map((word, index) => {
  26. if (words.length === index + 1 && !hasTrailingSpace) {
  27. // The last word - ok with the word being "startswith"-like
  28. return `(?=.*\\b${escapeRegExp(word)})`
  29. } else {
  30. // Not the last word - expect the whole word exactly
  31. return `(?=.*\\b${escapeRegExp(word)}\\b)`
  32. }
  33. })
  34. .join('') + '.+',
  35. 'gi'
  36. )
  37. return searchRegex.test(domain)
  38. } else {
  39. // if the query has non-ASCII chars, treat as other languages
  40. return words.some((word) => domain.toLowerCase().indexOf(word) > -1)
  41. }
  42. }