简体   繁体   中英

check if string contains url anywhere in string using javascript

I want to check if string contains a url using javascript i got this code from google

        if(new RegExp("[a-zA-Z\d]+://(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?").test(status_text)) {
          alert("url inside");
        }

But this one works only for the url like "http://www.google.com" and "http://google.com" but it doesnt work for "www.google.com" .Also i want to extract that url from string so i can process that url.

Try:

if(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(status_text)) {
        alert("url inside");
}

You can modify the regex to conditionally match on the scheme of the URL, like so:

var urlCheck = new RegExp('([a-zA-Z\d]+://)?(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?', 'i')
if (urlCheck.test(status_text) {
    console.log(urlCheck.exec(status_text));
}

Sudhir's answer (for me) matches past the end of the url.

Here is my regex to prevent matching past the end of the url.

var str = " some text http://www.loopdeloop.org/index.html aussie bi-monthly animation challenge site."
var urlRE= new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+");
str.match(urlRE)

produced this output using node.js:

[ 'http://www.loopdeloop.org/index.html',
'http://',
 undefined,
'www.loopdeloop.org',
 undefined,
'l',
index: 11,
input: ' some text http://www.loopdeloop.org/index.html aussie bi-monthly animation challenge site.' ]

试试这个

(?<http>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)
var reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
if (reg.test(status_text)) {
    alert(reg.exec(status_text)[2]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM