I am trying to validate a url where the "http:www" is optional, so the yahoo.com and http://www.yahoo.com needs to be valid url but using the following regex does not take utl3 to be valid one .
How can I fix this ??
function checkUrlTest(url){
var urlregex = new RegExp("^(https?:\/\/www\.)?(^(https?:\/\/www\.)[0-9A-Za-z]+\.+[a-z]{2,5})");
return urlregex.test(url);
}
url3 = "yahoo.com";
url4 = "www.yahoo.com";
alert(checkUrlTest(url3));
(http://)?(www\.)?[A-Za-z0-9]+\.[a-z]{2,3}
In this regex, http://www.yahoo.com, http://yahoo.com and www.yahoo.com are all valid URLs
Just check it out. All problems will resolve.
var rgx = /^\s*(http\:\/\/)?([a-z\d\-]{1,63}\.)*[a-z\d\-]{1,255}\.[a-z]{2,6}\s*$/;
Working Demo http://jsfiddle.net/fy66p/
Solution reside here: Negative Lookahead: http://www.regular-expressions.info/lookaround.html#lookahead with the www case and you should get what you are looking for. Lemme know how it goes!
Hope it fits your needs :)
code
function checkUrlTest(url){
// Try this
var urlregex = new RegExp("^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$")
return urlregex.test(url);
}
url3 = "yahoo.com";
url4 = "www.yahoo.com";
alert('===> ' + checkUrlTest(url4) + '===> ' + checkUrlTest(url3));
function validateUrl(value)
{
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(value);
}
if not try this:
(?i)\b((?:(?:[a-z][\w-]+:)?(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
Related
I have this regexp to extract instagram.com usernames
const matches = value.match(
/^(?:#|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/
);
console.log(matches[1])
It works fine with www.instagram.com/username but it doesn't work with www.instagram.com/username?ref=google
How can I exact only the username from the url?
Thanks for your help.
alternatively, do not use regex. e.g.
const url = "www.instagram.com/username?ref=google";
const oUrl = new URL("http://" + url);
console.log(oUrl.pathname.substring(1));
or
let url = "instagram.com/username?ref=google";
if (!url.startsWith("http://") || !url.startsWith("https://")) {
url = "http://" + url;
}
const oUrl = new URL(url);
console.log(oUrl.pathname.substring(1));
The $ at the end matches the end of the line, but the end of the username isn't necessarily the end of the line. To permit ? after the username as well, use (?:$|\?) instead of $:
^(?:#|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?(?:$|\?)
https://regex101.com/r/pbpi74/1
You can also try a non-regex way using .substring. You may find it cleaner than regex.
It works with both URLs.
let username = url.substring(
url.lastIndexOf("/") + 1,
url.lastIndexOf("?") > 0? url.lastIndexOf("?") : url.length
);
Check fiddle:
https://jsfiddle.net/whx5otvp/
I have a URL like below.
something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false
I want to replace the value of parameter showHiddenElements to some new value.
for e.g. exising value in URL -> showHiddenElements=false
I want to change it through JavaScript to -> showHiddenElements=true
Please advise.
Edit:
showHiddenElements may not always be false. And In some cases it may not be available.
Use the URL Object:
const url = new URL('http://something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false');
url.searchParams.delete('showHiddenElements');
url.searchParams.append('showHiddenElements', true);
So you just delete the parameter and update it with the new one (not the most elegant)
Docs here: https://developer.mozilla.org/fr/docs/Web/API/URL
You could use String.replace for that:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace('showHiddenElements=false', 'showHiddenElements=true');
You could also do it fancy and use regex:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace(/showHiddenElements=false$/, 'showHiddenElements=true');
The regex would only match showHiddenElements=false if it's on the end of the URL
To see if it's available you could use regex too:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
// If the url doesn't have a showHiddenElements=__any_word__
if (!url.match(/showHiddenElements=\w+/)) {
url = url + 'showHiddenElements=false';
}
var url = "something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false";
alert("Before: "+url);
url = url.replace("&showHiddenElements=false","&showHiddenElements=true");
alert("After: "+url);
//Console.log clips the end so we can't see the result :(
Maybe something liket this:
var loc = window.location.href;
var newLoc = loc.Replace('showHiddenElements=true', 'showHiddenElements=false')
A JavaScript Regular Expression should help if you are just treating the URL as a string.
var str = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
var res = str.replace(/showHiddenElements/i, 'true');
console.log(res);
I know that this question has been asked more than once here. But the issue I'm facing is a bit different that the one's I checked in previous questions.
I'm retrieving the Category in a variable from the URL in my JS by doing this-
$scope.category = url.split("=")[1]
This would be a sample URL-
sitename/pagename.aspx?Category=Cars
I'm facing an issue when there is a space in the category. Say if the URL is like this-
sitename/pagename.aspx?Category=Super%20Cars
Can you please lemme know how to replace the %20 by a space along with the url.split.
Sure this isnt a right one-
$scope.category = decodeURIComponent(url.split("=")[1]);
Lemme know if you need more info guys. :)
You can try this:
url.split('%20').join(' ');
You can do it by below syntax:
var url = window.location.href;
var tempUrl = url.replace(/%20/g," ");
$scope.category = tempUrl.split("=")[1]
You need to use decodeURI to achieve this.
http://www.w3schools.com/jsref/jsref_decodeuri.asp
Use decodeURI global function available in javascript. http://www.w3schools.com/jsref/jsref_decodeuri.asp
var url="http://www.dummyserver.com/index.php?param1=hello%20world";
var queryParams=url.substring(url.indexOf("?") + 1).split("&");
for(i=0;i<queryParams.length;i++){
var splitParam = queryParams[i].split("=");
alert("Param: " + splitParam[0] + " :: Value:" + decodeURI(splitParam[1]));
}
You can convert the url into string first and then replace %20 with the space and then split,it should work,can try like this:
var str = 'sitename/pagename.aspx?Category=Super%20Cars';
var res = str.toString();
res = res.replace('%20',' ');
category = decodeURIComponent(res.split("=")[1]);
I'm trying to come up with a regexp to get the page URL from the full URL but exclude a possible port number from it. So far I came up with the following JS:
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#]+)/i);
if(res)
{
var pageURL = res[1];
console.log(pageURL);
}
If I call it for this:
var url = "http://www.example.com/php/page.php?what=sw#print";
I get the correct answer: example.com/php/page.php
But if I do:
var url = "http://www.example.com:80/php/page.php?what=sw#print";
I need it to return example.com/php/page.php instead of example.com:80/php/page.php.
I can remove it with the second regexp, but I was curious if I could do it with just one (for speed)?
You can modify your regex to this:
/^.*\:\/\/(?:www2?.)?([^/:]+)(?:[^:]*:\d+)?([^?#]+)/i
RegEx Demo
It will return 2 matches:
1: example.com
2: /php/page.php
as match[1] and match[2] respectively for both inputs that you can concatenate.
http://www.example.com/php/page.php?what=sw#print
OR
http://www.example.com:80/php/page.php?what=sw#print
Update: Here are performance results on jsperf.com that shows regex method is fastest is of all.
Keep it simple:
~ node
> "http://www.example.com:3000/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
> "http://www.example.com/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
Why would you use a regex at all?
EDIT:
As pointed out by #c00000fd: Because document might not be available and document.createElement is very slow compared to RegExp - see:
http://jsperf.com/url-parsing/5
http://jsperf.com/hostname-from-url
Nevertheless I will leave my original answer for reference.
ORIGINAL ANSWER:
Instead you could just use the Anchor element:
Fiddle:
http://jsfiddle.net/12qjqx7n/
JS:
var url = 'http://foo:bar#www.example.com:8080/php/page.php?what=sw#print'
var a = document.createElement('a');
a.href = url;
console.log(a.hash);
console.log(a.host);
console.log(a.hostname);
console.log(a.origin);
console.log(a.password);
console.log(a.pathname);
console.log(a.port);
console.log(a.protocol);
console.log(a.search);
console.log(a.username);
Additional information:
http://www.w3schools.com/jsref/dom_obj_anchor.asp
How about a group for matching the port, if present?
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#\/:]+)(\:\d+)?(\/[^?#]+)/i);
if(res)
{
var pageURL = res[1]+res[3];
console.log(res, pageURL);
}
Try
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
document.body.innerText = res;
You could use replace method to modify your original string or Url,
> var url = "http://www.example.com/php/page.php?what=sw#print";
undefined
> var url1 = "http://www.example.com:80/php/page.php?what=sw#print";
undefined
> url.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
> url1.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
DEMO
I got few lines like these:
/coc59409.p?id=1218405784092
/acme-made-skinny-lray-orange/5616664.p?id=1218679205878
/incase-campus-brk-gray-pink-berry/7209107.p?id=1218833962192&skuId=7209107
and I need to delete in all of them what come after this ".p?id="
how can I do that?
results :
/coc59409.p?id=
/acme-made-skinny-lray-orange/5616664.p?id=
/incase-campus-brk-gray-pink-berry/7209107.p?id=
=> "/coc59409.p?id=1218405784092".replace(/\?.*$/,"")
>> "/coc59409.p"
You don't need a regular expression here - contextually what you are referring to is the query string of the URL and there are already tools in the DOM with the facility to tokenise this, for example:
var url = '/coc59409.p?id=1218405784092',
a = document.createElement('a');
a.href = url;
console.log( a.pathname ); // '/coc59409.p'
Details about the HTMLAnchorElement can be found here.
You could just split it,
var url = '/acme-made-skinny-lray-orange/5616664.p?id=1218679205878'
var urlArr = url.split('=');
console.log(urlArr[0]+'=');
Hope that helps :)
Take each line and replace id=[THE REST OF THE LINE] with id=.
Like so:
"coc59409.p?id=1218405784092".replace(/id=(.*)$/, 'id=')