简体   繁体   中英

Detecting URL with Regular Expressions

I am working on a website and I am needing help with a code that will evaluate to true if the URL is

stackoverflow.com/users/anytext

but not when the url is

stackoverflow.com/users/

Here is my code:

 <style> .hidden { display: none; }
 <body> <div style = 'height:200px; width:200px; background-color: blue;' class = 'testbox' id = 'testbox'></div> <script> function storeurl() { var testbox = document.getElementById('testbox'); varurl = document.URL; // it should be Global variable, so remove var if (varurl == 'file:///C:/Users/laptop%202/Desktop/test.html') { /* Need this to detect the url */ if(!testbox.classList.contains('hidden')){ testbox.classList.add("hidden"); }; } else { return varurl; }; }; document.onclick = storeurl; </script> </body>

I am trying to accomplish this with pure Javascript. I was looking into Regular Expressions but without much luck.

Without use of regex:

 var url = "http://stackoverflow.com/users/"; var test1 = "http://stackoverflow.com/users/anything"; var test2 = "http://stackoverflow.com/users/"; console.log(test1.length > url.length && test1.startsWith(url)); console.log(test2.length > url.length && test2.startsWith(url));

(but maybe not as flexible as when use regex....)

Cheers!

You can use the following regular expression:

stackoverflow\.com\/users\/[^\s]+$
  • You need to escape special characters like . and /
  • [^s] matches anything except whitespace characters. You could also use anything here .
  • + matches at least one of the preceding character (here [\\s] )
  • $ end of the string

Here is an example in JavaScript:

 var regex = /stackoverflow\\.com\\/users\\/[^\\s]+$/ var text1 = "http://stackoverflow.com/users/"; var text2 = "http://stackoverflow.com/users/anything"; console.log(!!text1.match(regex)); console.log(!!text2.match(regex));

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