I have a url in the formathttp://localhost:8080/testURL/location/#/old/Ds~1016,
The value 1016 will change based on the page selected.. is it possible in javascript to get the number 1016 part from url(based on page selected)???
Ive tried the function
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
You could also try it this way
window.location.href.split('~').pop(-1)
that should give you "1016"
Although the following would be better
window.location.href.split('/').pop(-1).split('~').pop(-1)
to make sure it is the last "/" element you are splitting
UPDATE
I always prefer using split() if it is for a single condition because the code is more understandable even though regex give better performance in the longer run. You can check the performance of regex vs split here
Try this:
regex = new RegExp("[0-9]*$");
regex.exec(window.location.hash);
To get the number, just use regex.exec(window.location.hash)[0], and then you may need to check whether it is 4 digits width.
I guess you can use the built-in window.location. And without regex you can do:
a = "http://localhost:8080/testURL/location/#/old/Ds~1016";
a.substring(a.indexOf("~")+1); // 1016
Or in a simpler way, you can use this:
window.location.hash.split('~')[1]
You can see the fiddle here: http://jsfiddle.net/DqzQF/
Feel free to try out all the URLs.
window.location.hash.split('~')[1]
Explanation:
We first grab the hash i.e. #/old/Ds~1016
by window.location.hash
Now, we split the hash with ~ (I assume that comes only one time in url)
split returns an array with Ds at 0th index and 1016 at 1st index.
So, finally
window.location.hash.split('~')[1] returns `1016`
Related
I'm trying to create a small script that detects whether the string input is either:
1) a URL (which will hold a filename): 'http://ajax.googleapis.com/html5shiv.js'
2) just a filename: 'html5shiv.js'
So far I've found this but I think it just checks the URL and file extension. Is there an easy way to make it so it uses an 'or' check? I'm not very experienced with RegExp.
var myRegExp = /[^\\]*\.(\w+)$/i;
Thank you in advance.
How bout this regex?
(\.js)$
it checks the end of the line if it has a .js on it.
$ denotes end of line.
tested here.
Basically, to use 'OR' in regex, simply use the 'pipe' delimiter.
(aaa|bbb)
will match
aaa
or
bbb
For regex to match a url, I'd suggest the following:
\w+://[\w\._~:/?#\[\]#!$&'()*+,;=%]*
This is based on the allowed character set for a url.
For the file, what's your definition of a filename?
If you want to search for strings, that match "(at least) one to many non-fullstop characters, followed by a fullstop, followed by (at least) one to many non-fullstop characters", I'd suggest the following regex:
[^\.]+\.[^\.]+
And altogether:
(\w+://[\w\._~:/?#\[\]#!$&'()*+,;=%]*|[^\.]+\.[^\.]+)
Here's an example of working (in javascript): jsfiddle
You can test it out regex online here: http://gskinner.com/RegExr/
If it is for the purpose of flow control you can do the following:
var test = "http://ajax.googleapis.com/html5shiv.js";
// to recognize http & https
var regex = /^https?:\/\/.*/i;
var result = regex.exec(test);
if (result == null){
// no URL found code
} else {
// URL found code
}
For the purpose of capturing the file name you could use:
var test = "http://ajax.googleapis.com/html5shiv.js";
var regex = /(\w+\.\w+)$/i;
var filename = regex.exec(test);
Yes, you can use the alternation operator |. Be careful, though, because its priority is very low. Lower than sequencing. You will need to write things like /(cat)|(dog)/.
It's very hard to understand what you exactly want with so few use/test cases, but
(http://[a-zA-Z0-9\./]+)|([a-zA-Z0-9\.]+)
should give you a starting point.
If it's a URL, strip it down to the last part and treat it the same way as "just a filename".
function isFile(fileOrUrl) {
// This will return everything after the last '/'; if there's
// no forward slash in the string, the unmodified string is used
var filename = fileOrUrl.split('/').pop();
return (/.+\..+/).test(filename);
}
Try this:
var ajx = 'http://ajax.googleapis.com/html5shiv.js';
function isURL(str){
return /((\/\w+)|(^\w+))\.\w{2,}$/.test(str);
}
console.log(isURL(ajx));
Have a look at this (requires no regex at all):
var filename = string.indexOf('/') == -1
? string
: string.split('/').slice(-1)[0];
Here is the program!
<script>
var url="Home/this/example/file.js";
var condition=0;
var result="";
for(var i=url.length; i>0 && condition<2 ;i--)
{
if(url[i]!="/" && url[i]!="."){result= (condition==1)? (url[i]+result):(result);}
else{condition++;}
}
document.write(result);
</script>
I need to alert user when the entered value
does"t start with http:// or https:// or //
if any of the above mentioned 3 words(http:// or https:// or //) were repeated in the entered
value.
I tried the below regex in which the 1st case succeeds where 2nd case fails
var regexp = /^(http:(\/\/)|https:(\/\/)|(\\\\))/;
var enteredvalue="http://facebookhttp://"
if (!regexp.test(enteredvalue.value)) {
alert("not valid url or filepath);
}
Please help me regarding the same.
This seems to work (though there will be more elegant solutions). Hope it helps at all.
var regex = /http[s]{0,1}:\/\/|\/\//;
var x = enteredvalue.split(regex);
if(!(x[0]=='' && x.length==2))
alert("not valid url or filepath");
Cheers.
Try
var regexp = /^(?!(.*\/\/){2})(https?:)?\/\//;
var enteredvalue = "http://facebookhttp://";
if (!regexp.test(enteredvalue)) {
console.log("not valid url or filepath");
}
A negative look-ahead is used to prevent a match if two sets of // appear in the string.
To check for multiple matches you could use String.match in conjunction with RegexP and the "global search" option. Below is a simplified version of your code:
var enteredvalue="http://facebookhttp://"
var test_pattern = new RegExp("(https://|http://|//)", "g"); //RegExP(pattern, [option])
enteredvalue.match(test_pattern); // should return ["http://", "http://"]
When match returns more than one instance then it is clear that the pattern is used more than once. That should help with identifying incorrect urls.
Also, it's alot cleaner than splits.
Hope this helps.
i want to break a following url
http://www.example.com?name=john&token=3425kkhh34l4345jjjhjhj&uid=09900434&cn=bella&cjid=3344324
into this by eliminating last two parametes i.e. &cn=bella&cjid=3344324
http://www.example.com?name=john&token=3425kkhh34l4345jjjhjhj&uid=09900434
the length of the url may change but the last two parameters remains in that position only. so how can i remove that in a efficient way.
A RegExp is the easiest way for this case:
str = str.replace(/&[^&]*&[^&]*$/,'');
You can use replace with regular expression. If the url is in var url then you can use this one
var new_url = url.replace(/&cn=.*/, '');
you can test it with
var url = 'http:\www.example.com?name=john&token=3425kkhh34l4345jjjhjhj&uid=09900434&cn=bella&cjid=3344324';
console.info(url.replace(/&cn=.*/, ''));
var string = "http://dom.com/?one=1&two=2&three=3&four=4";
string.match(/(.*)&(.*)&(.*)/)[1]; // strips last two parameters
You can use regular expressions to replace the last 2 parameters with the empty string:
var url = "http://www.example.com/?p1=1&p2=2&p3=3&p4=4";
var urlWithoutLast2Parameters = url.replace(/&[^&]+&[^&]+$/,"");
You could use the function IndexOf to find the location of the '&cn' and then just use the substring function to create a new string eliminating the '&cn' portion of the URL, so something like...
var intIndexOf = str.IndexOf('&cn=')
strURL = strURL.substring(0,intCharAt)
I am new to Javascript and recently I wanted to use regular expression in order to get a number from url and store it into a var as string and another var as digit. For example I want to get the number 55 from the below webpage (which is not an accrual page) and I want to store it in a var.
I tried this but it is not working
https://www.google.com/55.html
url.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
Please I need help but not with jQuery because it does not make a lot of sense to me.
var numPortion = url.match(/(\d+)\.html/)[1]
(Assumes a match; if it might not match, check the results before applying the array subscript.)
Try this
var a="https://www.google.com/55.html";
var match = a.match(/(\d+)(\.html)/);
match is an array,
match[0] contains the matched expression from your script,
match[1] is the number (the 1st parenthesis),
and so on
var url = 'http://www.google.com/55.html';
var yournumber = /(\d+)(\.html)$/.exec(url);
yournumber = yournumber && yournumber[1]; // <-- shortcut for using if else
I'm needing to extract a portion of an href attribute using javascript.
I've come up with a solution, but I'm not sure it's the best way. Below is my sample code. I've got a variable with the complete href path -- and all I'm interesting in extracting is the "Subcategory-Foobaz" portion.
I can assume it will always be sandwiched between the 2nd "/" and the "?".
I'm terrible with Regex, so I came up with what seems like a hokie solution using 2 "splits".
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/")[2].split("?")[0];
console.log(subcat);
Is this horrible? How would you do it?
Thanks
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/").pop().split("?")[0];
console.log(subcat);
Just a small change; use pop() to get the last element no matter how many /'s you have in your string
re = /\/[^\/]+\/([^?]+)/;
str = '/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about';
matches = str.match(re);
console.log(matches);