Rana Ghosh
Rana Ghosh

Reputation: 4674

How to remove unmatched part from string using JS/jQUery regex

I have regex /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\\=]*)/g for checking valid URL. But it accepts:

https://www.google.com
google.com
https://google.com
dev.google.com

Thats fine with me but I want that when user inputs these values filtered value will be google.com which I have to pass through AJAX but the inputs will be same on UI part ( means browser ). I know this is possible but I can't.

Any reference will be helpfull
Thanks in advance

Upvotes: 2

Views: 754

Answers (3)

Sinha
Sinha

Reputation: 512

Try

var regExp = /\w+\.\w+(?=$|\/)/;
var matches1 = regExp.exec("https://www.google.com/images");
var matches2 = regExp.exec("google.com");
var matches3 = regExp.exec("https://google.com");
var matches4 = regExp.exec("dev.google.com");


//matches1[0] contains the value between the parentheses
console.log(matches1[0]);
console.log(matches2[0]);
console.log(matches3[0]);
console.log(matches4[0]);

All of the above will give you 'google.com'

Upvotes: 1

revo
revo

Reputation: 48711

Check either matching section should appear at the end of URL or before any path, fragment or query string:

\w+\.\w+(?=$|[\/?#])

Live demo

Upvotes: 0

binariedMe
binariedMe

Reputation: 4329

Try the following regular exp. :

var a = /(\w*\.\w*)$|(\w*\.\w*)(\/)/;

Explanation :

first part of OR checks for last occurance of x.y second part of OR checks for x.y right before starting of "/" keyword

Upvotes: 0

Related Questions