我一直在寻找这个问题的答案,但我找到的所有答案都不是在 JavaScript 中。
我需要一种在 javascript 中检查字符串是否以 http、https 或 ftp 开头的方法。如果它不是以其中之一开头,我需要在字符串前面加上http://
。 indexOf 对我不起作用我认为我不需要 http、https 或 ftp。我也不想要类似的东西google.com/?q=http://google.com
触发它是有效的,因为它不以 http 开头,而 indexOf 会触发它是正确的(如果我没有完全弄错的话)。
我发现的最接近的 PHP 正则表达式是这样的:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
来源:如果 url 中不存在 http,如何添加 http https://stackoverflow.com/questions/2762061/how-to-add-http-if-its-not-exists-in-the-url
我只是不知道如何将其转换为 JavaScript。任何帮助将不胜感激。
export const getValidUrl = (url = "") => {
let newUrl = window.decodeURIComponent(url);
newUrl = newUrl.trim().replace(/\s/g, "");
if(/^(:\/\/)/.test(newUrl)){
return `http${newUrl}`;
}
if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
return `http://${newUrl}`;
}
return newUrl;
};
Tests:
expect(getValidUrl('https://www.test.com')).toBe('https://www.test.com');
expect(getValidUrl('http://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl(' http : / / www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('ftp://www.test.com')).toBe('ftp://www.test.com');
expect(getValidUrl('www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('http%3A%2F%2Fwww.test.com')).toBe('http://www.test.com');
expect(getValidUrl('www . test.com')).toBe('http://www.test.com');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)