我一直在寻找这个问题的答案,我发现的所有答案都不是用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;
}
Run Code Online (Sandbox Code Playgroud)
我只是不知道如何将其转换为javascript.任何帮助将不胜感激.
use*_*621 92
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;
};
Run Code Online (Sandbox Code Playgroud)
tsk*_*zzy 26
这应该工作:
var pattern = /^((http|https|ftp):\/\/)/;
if(!pattern.test(url)) {
url = "http://" + url;
}
Run Code Online (Sandbox Code Playgroud)
nic*_*nli 12
var url = "http://something.com"
if( url.indexOf("http") == 0 ) {
alert("yeah!");
} else {
alert("No no no!");
}
Run Code Online (Sandbox Code Playgroud)
非正则表达式声明方式:
const hasValidUrlProtocol = (url = '') =>
['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41031 次 |
最近记录: |