diff options
Diffstat (limited to 'src/shared/urls.js')
| -rw-r--r-- | src/shared/urls.js | 25 | 
1 files changed, 25 insertions, 0 deletions
| diff --git a/src/shared/urls.js b/src/shared/urls.js new file mode 100644 index 0000000..87b1a48 --- /dev/null +++ b/src/shared/urls.js @@ -0,0 +1,25 @@ +const trimStart = (str) => { +  // NOTE String.trimStart is available on Firefox 61 +  return str.replace(/^\s+/, ''); +}; + +const normalizeUrl = (keywords, searchSettings) => { +  try { +    return new URL(keywords).href; +  } catch (e) { +    if (keywords.includes('.') && !keywords.includes(' ')) { +      return 'http://' + keywords; +    } +    let template = searchSettings.engines[searchSettings.default]; +    let query = keywords; + +    let first = trimStart(keywords).split(' ')[0]; +    if (Object.keys(searchSettings.engines).includes(first)) { +      template = searchSettings.engines[first]; +      query = trimStart(trimStart(keywords).slice(first.length)); +    } +    return template.replace('{}', encodeURIComponent(query)); +  } +}; + +export { normalizeUrl }; | 
