在Javascript中检查字符串是否为url的函数
A function on checking if the string is a url in Javascript
我正在编写一个函数来检查输入字符串是否为Javascript中的url。我应该使用子字符串(0,6),看看是否以"http://"开始?还是有更好的实现方式?欢呼。
这样的代码应该可以处理简单的情况:
function is_url(url) {
return Boolean(url.match(/^https?:'/'//));
}
您可以使用正则表达式
/^http:'/'//.test(urlString)
您可以使用:
if(myvalue.indexOf('https://') == 0 || myvalue.indexOf('http://') == 0)
这取决于你想让它有多详细。我相信你可以在这里找到一个正则表达式你可以搜索一下
With regex:
/^http:/.test("http://example.com/")
如果您也想检查www
: /^(http:|www'.)/.test("http://example.com/")
要与众不同:
function matchString(str,matches)
{
if(matches)
{
matchString.toCheck=matches;
}
var matched = [];
for(var i=[0,str.length];i[0]<i[1]; i[0]++)
{
for(var j=[0,matchString.toCheck.length];j[0]<j[1]; j[0]++)
{
if(!matched[j[0]])matched[j[0]]={c:0,i:-1};
if(matchString.toCheck[j[0]][matched[j[0]].c]==str[i[0]])
{
matched[j[0]].c++;
if(matched[j[0]].i==-1)matched[j[0]].i=i[0];
}
else if(matchString.toCheck[j[0]].length!=matched[j[0]].c)matched[j[0]]={c:0,i:-1};
}
}
return matched;
}
var urlVariants = matchString("https://",["http://","https://","www."]);
var isUrl = false;
for(var i=[0,urlVariants.length]; i[0]<i[1]&&!isUrl; i[0]++)
{
isUrl = (urlVariants[i[0]].i==0);//index at the start
}
console.log(isUrl);
我认为regex是一个更好的解决方案:
function isAnUrl(url){
var expression = /[-a-zA-Z0-9@:%_'+.~#?&//=]{2,256}'.[a-z]{2,4}'b('/[-a-zA-Z0-9@:%_'+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (url.match(regex))
return true;
else return false;
}
相关文章:
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 如何检查这个代码点火器php函数是否工作,该函数是否在ajax url中使用
- iFrame url更改时执行函数
- 在javascript中使用split函数希望在页面加载时拆分url
- Reactjs URL.createObjectURL不是函数
- 将重定向URL链接添加到JS函数
- 如何使用特定的javascript函数创建一个url,以便在加载页面时运行
- 如何创建背景图像列表'URL,并使用jQuery在单击函数时应用它们
- 更新URL时使用Javascript函数显示日期
- ajax外部url加载完成后调用jquery函数
- 为什么html src属性中的相对url是因为Javascript函数中的完整路径
- 获取带有URL的字符串的Javascript函数
- 未捕获的类型错误:$(..).modal不是具有远程url的函数
- 如何在 javascript 中的 url 回调函数中传递参数
- 我如何向这个脚本添加一个点击按钮循环URL函数(按给定顺序在URL之间切换),或者这可能吗
- 通过 js/jquery 重定向 url 函数传递 php 变量
- 覆盖主干's从本地存储获取数据的URL函数
- 如何在loadXMLDoc(URL)函数的URL参数中从本地文件获取URL
- CodeIgniter相对路径或基URL函数
- 将有条件的spring MVC参数传入javascript url函数