From 09c5247dbadb468a764eef308634503484d398c5 Mon Sep 17 00:00:00 2001 From: Shin'ya Ueoka Date: Sat, 28 Jul 2018 23:47:26 +0900 Subject: Search keywords on paste --- src/shared/urls.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/shared/urls.js (limited to 'src/shared/urls.js') 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 }; -- cgit v1.2.3