Use JS or jQuery to replace part of a URL - javascript

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

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 h ref not correctly matched

In my web app I have various .jspx pages, in one of this I want compose it dinamically by javascript.
I want to create a table with the data element, every data element have an index.
I compose a var, named url, with the path and the id of element:
var url = "${downloaHistodyUrl}"+data[index].id;
My problem is that the url is set correctly (I had used the alert for debug it). But, when I click on: <a href> element I have the "url" world, instead of the value of the variable and my path is: "/mypath/"+url+ .
CODE:
$('#modal_history_${doc.id}').on('show.bs.modal', function(e) {
$.getJSON('${historyUrl}', function(data) {
var html='<table class="table table-hover"><tr><th>Versione</th><th>Nome</th><th>PDF</th><th>Motivazione</th></tr>';
$.each(data, function(index) {
html = html+"<tr><td>"+data[index].versione+"</td>";
if(data[index].fileName != null){
var url = "${downloaHistodyUrl}"+data[index].id;
alert(url);
html = html+'<td>'+data[index].fileName+'</td><td> Download</span></td>';
}else{
html = html+"<td></td>";
}
if(data[index].motivazione == "" || data[index].motivazione == null){
html = html+"<td></td>";
}else{
html = html+"<td>"+data[index].motivazione+"</td>";
}
html = html+'</tr>';
});
html = html+'</table>';
$('#content_modal_history_${doc.id}').append(html);
})
});
I don't understand why..
Anyone can help me?
You're missing the double quotes on the href attribute.
You have <a href=myurl while it needs to be <a href="myurl"
Also, double-check that you really used single quotes when adding url to the string and not double quotes. If you did something like this, it would exactly cause the problem you're describing:
html = 'click me'
Your code should read like this:
html = html+'<td>'+data[index].fileName+'</td><td><span class="fa fa-download"> Download</span></td>';
The problem is that you need to escape the slash '/' characters in your url variable. Otherwise they will have the effect you are experiencing, that is, they will make the single quotes appear in the final output.
Edit: In case you didn't understand, what I mean is changing/replacing the slashes (/) with double slashes like (//). I also recommend you to use the concat method instead of using the add (+) operator for strings, for a cleaner code.

Get href value from a variable

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

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!

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