I need to parse long urls and set a variable (category) equal to one of the /folders/ in the path.
For example, a url that is
http://example.com/community/home/whatever.html
I need to set the variable equal to whatever folder path comes after /home/ in that url.
I've got this to alert me with what comes after /community/, but then the url turns to NaN and the link doesnt work. I think I'm not on the right track.
if ($(this.href*='http://example.com/community/')){
var category = url.split("community/");
alert(category[category.length - 1]);
}
Thoughts?
TIA.
You can fetch everything after the "/community/" with a regular expression:
var url = "http://www.example.com/community/whatever";
var category = "";
var matches = url.match(/\/community\/(.*)$/);
if (matches) {
category = matches[1]; // "whatever"
}
Working example here: http://jsfiddle.net/jfriend00/BL4jm/
If you want to get only the next path segment after community and nothing after that segment, then you could use this:
var url = "http://www.example.com/community/whatever/more";
var category = "";
var matches = url.match(/\/community\/([^\/]+)/);
if (matches) {
category = matches[1]; // "whatever"
} else {
// no match for the category
}
Workikng example of this one here:http://jsfiddle.net/jfriend00/vrvbT/
When you do this.href*= you're doing multiplication, and that's why you're getting not-a-number. It multiplies this.href by the string and assigns that to href.
If you mean to test whether the url starts with that string you can do it like this, no need for jQuery:
var start = 'http://example.com/community/';
if (url.substring(0, start.length) === start)){
var category = url.split("community/");
var lastPart = category[category.length - 1];
return lastPart.split("/")[0];
}
Related
I have to extract a specific part from an url origin. But I can't seem to figure out a good and fail proof way to do this
For example, this is my url:
http://site.domain.com
I need to know what "domain" is used. How do I get this part from the url 100% of the time?
My first thought was to split it between the "." but then I thought about what could happen if someone uses a http://www.site.domain.com link. That would mean it wouldn't work.
Further explanation:
I currently have 2 website which both have a differend domain name. I have to get the information about which page is loaded, based on the "domain" name in the url.
Thanks in regard!
split the full domain name on dot and than take element before last element.
var url = 'http://www.site.domain.com';
var array = url.split(".");
var lengthOfArray = array.length;
var domain = array[lengthOfArray-2];
console.log(domain);
Split by / using split("/"):
function getDomain(url){
var arr = url.split(".");
return arr[arr.length - 2];
}
console.log(getDomain('http://site.domain.com'));
console.log(getDomain('http://www.site.domain.com'));
You could split it by "." and get the next to last text of your string.
var str = 'http://www.site.domain.com';
var domain = str.split('.');
console.log(domain[domain.length-2]);
Later Edit
To provide further fail proof, you can get the latest text between .com and the first dot before it. This will work in case you have another dot in your URL, for example: 'http://www.site.domain.com/post/test.asp'.
var str = 'http://www.site.domain.com/post/test.asp';
var preComLink = str.substr(0, str.indexOf('.com'));
var preDomainIndex = preComLink.lastIndexOf('.');
var domain = preComLink.substr(preDomainIndex + 1, str.indexOf('com'));
console.log(domain);
let code = (function(){
return{
getDomain: function(url){
var slpitDomainURL = url.split(".");
var lengthOfArray = slpitDomainURL.length;
var domain = slpitDomainURL[lengthOfArray-2];
return domain;
}
}
})();
console.log(code.getDomain('http://www.google.com'));
console.log(code.getDomain('http://www.facebook.com'));
I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).
I have an url that looks like this:
http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg
I want to extract hw6dNDBT.jpg, from the url above.
I tried playing around with regex patterns /img\/.*-/ but that
matches with img/hw6dNDBT-.
How can I do this in JavaScript?
try this:
var url = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
var filename = url.match(/img\/(.*)-[^.]+(\.[^.]+)/).slice(1).join('');
document.body.innerHTML = filename;
i would use split() method:
var str = "http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg";
var strArr = str.split("/");
var size = strArr.length - 1;
var needle = strArr[size].split("-");
var fileTypeArr = strArr[size].split(".");
var name = needle[0]+"."+fileTypeArr[fileTypeArr.length-1];
name should now be your searched String so far it contains no / inside it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
/[^\/]+$/ should match all characters after the last / in the URL, which seems to be what you want to match.
No regex:
//this is a hack that lets the anchor tag do some parsing for you
var parser = document.createElement('a');
parser.href = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
//optional if you know you can always trim the start of the path
var path = parser.pathname.replace('/assets/uploads/');
var parts = path.split('/');
var img = '';
for(var i=0; i<parts.length; i++) {
if (parts[i] == 'img') {
//since we know the .jpg always follows 'img/'
img = parts[i+1];
}
}
Ah, you were so close! You just need to take your regex and use a capturing group, and then add a littttle bit more!
img\/(.*)-.*(\..*)
So, you can use that in this manner:
var result = /img\/(.*)-.*(\..*)/.exec();
var filename = result[1] + result[2];
Honestly capturing the .jpg, is a little excessive, if you know they are all going to be JPG images, you can probably just take out the second half of the regex.
Incase you are wondering, why do we uses result[1] and result[2]? Because result[0] stores the entire match, which is what you were getting back. The captured groups, which is what we create when we use the parentheses, are stored as the indexes after 0.
Here is some one-liner:
var myUrl = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg',
myValue = myUrl.split('/').pop().replace(/-(?=\d).[^.]+/,'');
We take everything after the last slash then cut out the dimension part.
I have a regex to get #user from a textarea. When user type something with # I get it.
My problem is, I want to get just the last match, not all of them.
eg:
user type:
#josh and #marie = want to show #marie
#josh loves #marie and #anne = show #anne
my code is showing like this:
#josh,#marie,#anne
Can I get just the last #something entry? (while user is typing)
var word=/#(\w+)/ig;
$("#comment").on("keyup",function() {
var content = $(this).val();
var name = content.match(word);
var dataString = name;
if(name.length > 0) {
$("#result").text(name);
}
return false();
});
html
<textarea id=comment>#josh and #marie</textarea>
<div id=result></div>
https://jsfiddle.net/dcs5pat8/ (press on textarea)
Besides getting all matches and obtain the last one, you can use capture groups to get the last match:
var word=/.*(#\w+)/i;
var name = content.match(word)[1];
Or using exec, the whole would look like:
var word=/.*(#\w+)/i;
$("#comment").on("input",function() { //changed keyup to input
var content=$(this).val();
var match = word.exec(content);
if(match){
$("#result").text(match[1]);
}
});
Fiddle
PS, if your goal is a more generic approach and you need to switch between getting all words and a single one, I'd recommend keeping the global match and getting the last as in Jonas' answer.
My suggestion is that you show only the last entry of your results.
You can do that by changing the line:
var name = content.match(word);
to
var names = content.match(word);
var name = names[names.length - 1];
On more detail, what this does is it gets all the results from your regex, then it attributes the last item of the array to the name variable.
Hope this was helpful.
You can simply select or pop the last match in the array of match returned by .match()
var word=/#(\w+)/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var matches = content.match(word);
var lastmatch = matches.pop();
//IF YOU NEED TO KEEP INTACT THE VAR MATCHES
//var lastmatch = matches[matches.length - 1];
if(name.length>0){
$("#result").text(lastmatch);
}
return false();
});
JSFiddle
Use this regex '/#(\w+)$/ig' insted of '/#(\w+)/ig'.
And then your code will run like a charm. ;)
var word=/#(\w+)$/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var name = content.match(word);
var dataString = name;
if(name.length>0){
$("#result").text(name);
}
return false();
});
See it hear https://jsfiddle.net/dcs5pat8/1/
I do like the answer where you take your list with all of the #names,#name1,#name2 and just split off the last one, but here it is in just one step
//split on #something
//the penultimate item is our target
//if there is < 2 items there weren't any #somethings so return ''
user = (split = "testing #charlie testing".split(/(#[^ ]*)/)).length > 1 ? split.splice(-2,1)[0] : '';
https://jsfiddle.net/ek19h0fb/1/
To have only one line you can do
var name = content.match(word).reverse()[0];
I have the following link:
sitename.com/Default.aspx?PageID=13078494
I want to grab the following: "PageID=13078494". This is what I have so far:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match([PageID=13078494]);
urlmatch[0];
Is this the proper expression for what I'm trying to do?
Your regex and its syntax are wrong.
A better way would be to not use a regex at all. Use .split() instead:
var urlmatch = url.split('?')[1];
Here's the fiddle: http://jsfiddle.net/qpXNU/
var myregexp = /[?&]PageID=(\d+)/i;
var match = myregexp.exec(url);
if (match != null) {
//This is if your match it successful
result = match[1];
} else {
//This is if url doesn't match
result = "";
}
This one will work regardless of where PageID is. It will match
sitename.com/Default.aspx?PageID=13078494
anything.org/Default.aspx?PageID=13078494
sitename.com/Default.aspx?foo=bar&PageID=13078494
sitename.com/Default.html?foo=bar&PageID=13078494&bar=foo
Default.html?foo=bar&PageID=13078494&bar=foo
Importantly, it WON'T match
sitename.com/Default.aspx?NotThePageID=13078494
Or without the checking, simply
url.match(/[?&]PageID=(\d+)/i)[1], but I'd advice against that unless your SURE it will always match.
Try the following regex, which will extract the PageID and place it in the first match group:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match(/PageID=(\d+)/);
alert(urlmatch[1]); // 13078494
If you are matching specific value, then it's fine, otherwise use below to match any number of digits in pageID:
/PageID=\d+/
as:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d+/);
alert(urlmatch[0]);
or to match 8 exact digits in pageID, use:
/PageID=\d{8}/
as:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d{8}/);
alert(urlmatch[0]);
When it comes to handling URLs, the browser is pretty good.
You should convert your string to an actual URL like so:
var toURL = function (href) {
var a = document.createElement('a');
a.href = href;
return a;
};
Now use the browser's built-in parsing capabilities:
var url = toURL('sitename.com/Default.aspx?PageID=13078494');
alert(url.search);