Get href value from a variable - javascript

I have been trying to take out the href value from a variable which contains a link.
This is my variable which contains a link.
var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>"
I tried to get the value #!takethisout , and I also googled it but there are bunch of pages with how to get the href value from a real link.
Is this possible? Thanks.

I could be wrong, but I think you're asking for a documentFragment so you can extract the href from the string:
var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>";
var div = document.createElement('div');
div.innerHTML = mylink;
var href = div.firstChild.getAttribute('href');
http://jsfiddle.net/userdude/js8r2/

If you can use jQuery you could do it like this:
var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>";
var href = $(mylink).attr('href');
alert(href);
Example: http://jsfiddle.net/pn8M4/

What about string split?
var hrefAttr = mylink.split(/href='(.*?)'/)[1]
http://jsfiddle.net/SzHLu/

You need regular expression to parse part string.
mylink.match(/href=["']([^"']+)["']/i)[1];
mylink.split(/href=["']([^"']+)["']/i)[1];
Beware - it doesn't actually parses html and looking for href attribute - it will only find string matching regular expression. so in this case
<a href=#!foobar>
it will NOT work
upd: using split will not break the code in case of non-existent match - thanks #freshbm

Related

correct a bad generated link using Javascript

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

Creating a link tag with parameters

Hi i have a link tag that i am creating from javascript. now i want to append a parameters to that link just like below example.so that when the user clicks that button it should go to that url along with the paramenters
var id="123456789";
var data = ' click' ;
this data tag i am appending to some other element.
now i can able to call /order/product. but when i give id also it is giving error "missing arguments"!!
can anyone please help me?
You'll have to unquote the string where the variable goes
var id = "123456789";
var data = ' click' ;
Or on really up-to-date JavaScript engines that support ES2015+ template literals:
var id = "123456789";
var data = ` click`;
But that won't work on any version of IE (does on Edge).
For easy create link you can use method link(str) of String:
var id="123456789";
var linkText = " click";
var href = "/order/product/" + id;
var data = linkText.link(href);
alert(data);
To make it easier both to write and read (and debug too), I'd recommend the following variant of how to organize the code:
var id = "1234566",
// It is more understandable now that hrefLink contains id concatenated with some other string
hrefLink = "/order/product/" + id,
link = document.createElemen('a');
link.href = hrefLink;
In this way you
See what variable means what
Control what your hrefLink consists of
Follow best practises when instead of multiple lines with var statement you explicitly "show" where the declaration section is:
var a = smth1,
b = smth2;
So just by looking at this code you easier understand that that is a code chunk of variables declaration
You just need to remove the quotes from id
just like below
var id="123456789";
var data = ' click' ;
If You have id within quotes means it will take as string not a variable name and so just remove the quotes. It will work

How to get "onclick" value JS

I would like to know if is possible to get onclick value using Javascript.
I have this link:
<a onclick="window.open('WhatIWantToGet')"></a>
and I would like to get "WhatIWantToGet".
You can get the parameter to the function by getting the onclick attribute of the DOM node and parsing out the argument:
var link = document.querySelector('a');
alert(link.getAttribute('onclick').match(/'(.*)'/).shift());
Basic regular expression to parse the onclick attribute. This assumes it will be single quotes around the string.
var anchor = document.querySelector("a");
var re = /window\.open\('([^']+)/;
var txt = anchor.getAttribute("onclick").match(re);
console.log(txt ? txt[1] : "no match");
<a onclick="window.open('WhatIWantToGet')"></a>

Use JS or jQuery to replace part of a URL

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];
});

javascript or jquery - get the last 2 characters of href

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.

Categories

Resources