Creating a link tag with parameters - javascript

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

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

Javascript/jQuery - Need to find raw text on the page, capture what follows into variable, and replace original with HTML

So let’s say the text KEYWORDANIMAL:(Cat) appears on a page. I want to search through the page for all instances of KEYWORDANIMAL, and then pull the actual animal, in this case Cat, into a variable to be used in another script that’ll pull in related content. I also want to replace KEYWORDANIMAL:(Cat) with an empty div with concatenated ID to be targeted by the other script (this other script is already working fine by itself).
I've been using info from several other threads here but just cannot make it all come together.
-Find text string using jQuery?
-Get text from character and after using jQuery
-How do I use JQuery to replace all occurring of a certain word in a webpage?
Here's what I have so far:
<p>Here is an animal: KEYWORDANIMAL(Cat)</p>
var findString = $('p:contains("KEYWORDANIMAL")').html();
var startIDString = findString.indexOf('(') + 1;
var endIDString = findString.indexOf(')');
var animalID = findString.substring(startIDString, endIDString);
var embedString1 = "<div id=\"";
var embedString2 = "\"></div>";
var embedStringFull = embedString1 + "animal" + animalID + embedString2;
alert(embedStringFull);
findString.each(function () {
var newDIV = $(this).html().replace('KEYWORDANIMAL', embedStringFull);
$(this).html(newDIV);
});
In fiddle form: http://jsfiddle.net/dC6bj/1/
I got the find part down (probably not very efficiently though), but I am clearly missing something on the replace.
If you absolutely have to do this with JavaScript, you can use a regex replacement function:
var animal_regex = /KEYWORDANIMAL\((.*?)\)/g;
$('p:contains("KEYWORDANIMAL")').each(function() {
var $this = $(this);
var html = $this.html().replace(animal_regex, function(match, name) {
return '<div id="animal' + name + '"></div>';
});
$this.html(html);
});
Demo: http://jsfiddle.net/dnuaL/
This should be done serverside, if possible.
For your third question on how toreplace all occurences of a certain word in a webpage use Regex.Replace like this:
var pagecontent = $('body').html();
var newcontent = Regex.Replace(pagecontent , #"[cat]", "dog");
&('body').html(newcontent);
Regex is the fastest solution for this kind of stuff.
My code example is a bit simple, it would also replace ocurrences within a tag.
or within a word for example in catamaran or .
To make it more perfect you could look for cat preceded by a space and followed by a space or a point or a comma. Read some regex tutorials for this. (It's really worth learning, once you know how to, you'll use it a lot)
Goodluck!

Replace element with text with javascript (no jquery)

I'm trying to create a link which has a dynamic value in it
http://my.link/index.php?action=huh&id=X
The X is what i want to replace dynamically with javascript variable.
I don't want to use jquery for it.
AND, i do not want to replace the whole url(href) because some part of URL needs to parsed by the template engine.
I think it'd be better if i inserted an element in place of X and replaced it with JS
only replace id
var elLink = document.getElementById("link");
elLink.href = elLink.href.replace(/id=(.*)/, function(){return "id=2"});
if id=X is constant
elLink.href = elLink.href.replace("id=X", "id=2");
You can use something like
document.getElementById("YourAnchorId").href= document.getElementById("YourAnchorId").href + id;
or
document.getElementById("YourAnchorId").href= document.getElementById("YourAnchorId").href +"?id" + id;
And that id variable get it from a textbox or however you need it.
And whats its the reason for not using jquery?

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

Use variable in new variable

I'm trying to add a variable within a new variable.
My first variable is:
var video5 = myObj.find('hosted-video-url').text(); (this returns a direct link to an mp4-file)
My second one should be something like:
var playvid5 = "playVideo('"video5"')";
Variable playvid5 should result "playVideo('http://link.to/video.mp4)')"
When I try to make variable playvid5 in the way I showed above, my whole code stops working and nothing is displayed. When I use var playvid5 = "playVideo('"+video5+"')";, the output is "playVideo('')", so that's not what I need either.
I'm trying to place the 2nd variable in this piece: ('Bekijk video')
In what way can I place the first variable in the second one?
Try to replace video5 string by its value.
var video5 = myObj.find('hosted-video-url').text();
var playvid5 = "playVideo('video5')";
playvid5 = playvid5.replace("video5", video5);
Why not just give the <a> tag an "id" value, drop it in the document, and then do:
$('#whatever').click(function() { playVideo( video5 ); });
Now, where you go to find the value, I don't think you've got the correct selector. Probably you need
var video5 = myObj.find('.hosted-video-url').text();
The "." before the string "hosted-video-url" is to select by class name. If "hosted-video-url" is an "id" and not a class, then you don't need to use .find(); you can select by "id" with $('#hosted-video-url').
Do you mean
var playvid5 = "playVideo('" + video5 + "')";
playvid5 will then be the string "playVideo('http://whatevervideo5is')
if video5 is blank then you will get "playVideo('')" so maybe that is the issue.

Categories

Resources