0

I have the form on my page with text url field. User can input there any value, like:

How can I validate that correct domain is given (example.com) and then extract topic id (557761)?

Looks like I should use jQuery.isNumeric first (to capture last case), if it is not numeric, then I can extract the value like /^.*t=(\d+)$/. But how should I check the domain in the regex?

LA_
  • 19,823
  • 58
  • 172
  • 308
  • Use `document.domain` to get "example.com" or whatever the page's value is. – Ian Dec 08 '12 at 08:46
  • And use the accepted answer from this - http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values - to get the value for the "t" item in the querystring (topic id) – Ian Dec 08 '12 at 08:49

4 Answers4

1

This will work for all cases except the last case which you said you already have a solution for.

var pattern = "^(?:http(?:s)?://)?(?:www\.)?example\.com/forum/viewtopic\.php\?t=(\d+)";
var regex = new RegExp(pattern, "i");
var match = regex.exec(string);
if (match) {
    alert(match[1]);
}

If you don't mind a less readable regex pattern then the following will work to capture all your cases (including the last one). Just replace the pattern line in the above code with the one below.

var pattern = "(?:(?:^(?:http(?:s)?://)?(?:www\.)?example\.com/forum/viewtopic\.php\?t=(\d+))|(^\d+$))";
Tanzeel Kazi
  • 3,797
  • 1
  • 17
  • 22
0

This should do the work:

var domain = "example.com"
var regex = "http://(www)?"+domain+"/.+?t=([0-9]+)";
var match = regex.exec(inputString);
var topicId = match[1];
RePierre
  • 9,358
  • 2
  • 20
  • 37
0

You can leverage the browser's URL parser using an <a> element:

var myhost = "example.com";

// Here url is the data given in the text input field
var hostname = $('<a>').prop('href', url).prop('hostname');
if (myhost == hostname) {
    alert('Host matched!');
}​
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

(?<=example\.com/forum/viewtopic.php\?t=)\d+(?=\&)

http://regexr.com?33333

This should work for you.

Jack
  • 5,680
  • 10
  • 49
  • 74