I need to get the last 2 characters from the href of a link and place them into a string.
I'm sure this is fairly simple but I seem to be struggling.
Here's the link
test
I need to grab the "bb" part of the href.
Presuming link is a reference to the element:
var chars = link.href.substr(-2);
If you need to get the reference to the link, it is best to give the link an ID attribute, e.g. <a href="../mypage/?code=bb" id="myLink">, where myLink is something that describes the link's purpose. You can then do this:
var chars = document.getElementById('myLink').href.substr(-2);
Finally, if what you want is the code parameter from your link, it may be best to parse the URL into parts. If there is a chance that your URL may be more complex that what you've shown, you should do real URL parsing. As Rahul has pointed out in his answer there are some jQuery plugins that perform this function.
try
$(function() {
var res = $('a').attr('href').split(/=/)[1]
alert(res);
});
This will not grab the last two character, but everything after the = sign which works probably more generic. And even if the <center> cannot hold, regex could look like
$(function() {
var href = $('a').attr('href'),
res = /\\?code=(\w+)/.exec(href);
alert(res[1]);
});
var href = $('a').attr('href');
var last2char = href.substr(href.length-2);
You can try for some querystring plugins which might be a better option.
Related
I have a system that dynamically generates links. but the html links are displayed like this :
Page Example
there's a way to remove the repetition of <a> tags using JS ? so, the link becomes :
Page Example
Let's take a look at your url:
var url='Page Example';
First let's get rid of both occurences of "
url=url.replace(/"/g,'');
Now remove the first occurence of </a> by feeding the exact string instead of a regular expression to the .replace method.
url=url.replace('</a>','');
At this point your url looks like this:
Page Example
We're getting closer. Let's remove anything in between the > and the " by
url=url.replace(/\>(.*)\"/,'"');
which gives us
Page Example
Almost done - finally let's get rid of "<a href=
url=url.replace('"<a href=','"');
To make the whole thing a bit more beautiful we can chain all four operations:
var url = 'Page Example';
url = url.replace(/"/g, '').replace('</a>', '').replace(/\>(.*)\"/, '"').replace('"<a href=', '"');
console.log(url);
Within your process you can use regex to extract the url from the href string:
const string = "<a href="/page-example">Page Example</a>";
const url = string.match(/(\/)[\w-]*(?=&)/)[0];
console.log(url);
Yes, using the string split() function like this...
S='<a href="/page-example">Page Example</a>';
var A=split('"');
document.write(A[1]);
This should display "/page-example", and you can then add it as the href to an anchor.
You can retrieve the hrefvalue that seems to be the correct A element and replace the incorrect one with the correct one:
const a = document.querySelector('a[href]'); //if you have more <a> elements replace it to your need
const attr = a.getAttribute('href'); //get the value of 'href' attribute
const temp = document.createElement('template');
temp.innerHTML = attr; //create the new A element from the 'href' attribute's value
const newA = temp.content.children[0]; //retrieve the new <a> element from the template
a.parentElement.replaceChild(newA, a); //replace the incorrect <a> element with the new one
Page Example
I have a link example this
Now I want to get the source of this page and extract the md5 hash value which is something like
<strong>MD5:</strong> 1b061e5530d2612135b8896482e68e3c</div>
<div>
I want to get the value 1b061e5530d2612135b8896482e68e3c from it.
I have made an GET request and got the source code in an variable like:
$.get(link).done(function(data){
alert(data);
});
This seems to be working fine but I have no Idea how to proceed further kindly help me .
I have Searched but not got any helpful result.
You could use good, old fashioned regexp (i.e., the second result of /MD5:<\/strong> (.*?)<\/div>/g).
var result = (/MD5:<\/strong> (.*?)<\/div>/g).exec([text])[1];
var regex = /MD5:<\/strong> (.*?)<\/div>/g;
var output=document.getElementById("output");
var test="<strong>MD5:</strong> 1b061e5530d2612135b8896482e68e3c</div>";
var matches = regex.exec(test);
output.innerHTML="MD5 is "+matches[1];
<div id="output"></div>
You can use xpath to get the text node containing the MD5 hash value:
$.get(link).done(function (data) {
var md5Node = document.evaluate('//*[#id="app_info"]/div[1]/div[2]/div[2]/div[1]/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var md5String = md5Node.textContent;
// ...
});
A better XPath
It would be better to find the MD5 text node based on its sibling's value. The XPath would look like
//*[text()="MD5:"]/../text()
Does the div you're trying to get the value from have an ID? If so you could try something like this
$.get(link).done(function(data){ console.log($(data).find("#idofdiv").text()); });
You could also use jQuery's .load function, like this:
$('div#container').load('external-page.html div#md5');
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.
Ok, I am not sure what is wrong with me, but I am trying to find and replace a portion of multiple URLs.
Basically, I have some URLs that are being dynamically added to my site. All have a class of 'newsLink' some of the links are pulling up google.docs viewer and I need to remove that.
Here is my code thus far:
$('a.newsLink').each(function(){
var lnk = $('a.newsLink').attr();
var re = new RegExp("http://docs.google.com/viewer?url=","g");
lnk.replace(re, "");
});
the links look like:
<a href='http://docs.google.com/viewer?url=myHomePage.pdf' class='newsLink' target='_blank'>
I would like to remove the first part so that the link looks like:
<a href='http://myHomePage.pdf' class='newsLink' target='_blank'>
Anyway, no luck this far...can anyone please help.
First, you are getting all links again inside of the loop. Then, you try to get an attribute, but didn't say which one. Finally, you try to use replace without assigning the return value to anything.
This is what your code should be:
$('a.newsLink').each(function(){
var lnk = this.href;
this.href = lnk.replace("http://docs.google.com/viewer?url=", "");
});
Note: I'm assuming you want the links to become e.g. myHomePage.pdf, without the protocol.
The regular expression you want is.
http:\/\/docs\.google\.com\/viewer\?url=(.+)
First off, this escapes all regular expression characters. In this case \, ., and ?. We are capturing the document using a group that matches every character ((.+)).
So our code looks like this so far.
$('a.newsLink').each(function(){
var lnk = this.href;
var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
this.href = lnk.replace(re, "");
});
Now we get the groups like so.
var match = re.exec(lnk);
This returns an array of the matches. Our document is now stored in match[1]. So our final code comes out to.
$('a.newsLink').each(function(){
var lnk = this.href;
var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
this.href = (re.exec(lnk))[1];
});