i want to mark a bookmarklet which can match my enter words.
if enter words are url like http://,
then open it,
otherwish use google to search it!
here is my code below, but it seems not working!!
javascript:var x=prompt('Enter url or text!','');
let url = x;
try {
var reg = /^http[s]?:\/\/(www\.)?(.*)?\/?(.)*/;
if (!reg.test(url)) {
url = 'https://www.google.com/search?q=' + encodeURIComponent(url);
}
else {
if (url.substring(4, 0).toLowerCase() == "http") {
url = encodeURIComponent(url);
}
else {
url = 'http://' + encodeURIComponent(url);
}
}
};
use bookmarklet way!
The code is fine, except it fails to match on URLs like www.stackoverflow.com
(without the http[s]
) and also it's encoding the forward slashes when http[s]
is provided.
www.stackoverflow.com
encodeURIComponent
to encodeURI
for URLs that already have http[s]
.Note: This solution won't work for urls such as stackoverflow.com
which are missing both the www.
and http[s].
prefixes.
javascript:(function() {
var x=prompt('Enter url or text!','');
let url = x;
try {
var reg = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/;
if (!reg.test(url)) {
url = 'https://www.google.com/search?q=' + encodeURIComponent(url);
} else {
if (url.substring(4, 0).toLowerCase() == "http") {
url = encodeURI(url);
}
else {
url = 'http://' + encodeURIComponent(url);
}
}
window.location.href = url;
} catch(err) {
console.error(err);
}
})();