replace matching text in hyperlink href - javascript

What im trying to do is find all hyperlinks that have a href like this herf="/grade4/chapter1.html"
and replace the chapter word with href="grade4/chapter_af1.html"
i have tried a few jquery tricks but have had no luck
$('a').each( function() {
var $this = $(this);
var href = $this.attr('href').replace(/\chapter/,'chapter_af');
$this.attr('href', href );
});

You don't need a regular expression, just do a normal string replace:
http://jsfiddle.net/9MXSZ/
$('a').each( function() {
var $this = $(this);
var href = $this.attr('href').replace('chapter','chapter_af');
$this.attr('href', href );
});
If you really want to use a regex, the \ in your version is throwing it off:
.replace(/chapter/,'chapter_af')

No need of Regex here.
Try simply like this
var href = $this.attr('href').replace('chapter','chapter_af');

Just change your replace statement to:
...
var href = $(this).attr('href').replace('chapter', 'chapter_af')
...
See it working here: http://jsfiddle.net/vNCpV/

Related

Trim partial link in jQuery

I am trying to remove the start of a link in jQuery. I have tried to inject the following function but it doesn't work. What am I doing wrong?
JS
$(function() {
$('link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
HTML
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
When you're trying to search for classes, make use of dot (.), $('link-active') should be $('.link-active').
About .remove(): this one will remove one element of the DOM; not applicable in this case.
Solution: You will need to use .attr() to return AND update the href attribute of your tag, .replace() method should help.
$(function() {
$('.link-active').each(function() {
let href = $(this).attr('href'); //returns href value
let removableUrl = 'http://www.linkplus.com/xQWE=';
href = href.replace(removableUrl, ''); //replace the url you don't want with ''
$(this).attr('href', href); //update href value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
Note: There's other methods to separate the url you don't want (if the url stay in the same format), check for:
.substring(): href = href.substring(removableUrl.length);
.split(): href = href.split('=')[1];
.replace() with regex: href = href.replace(/.*\=/,'');
Amend $('link-active') to $('.link-active').
First thing is While representing a class in jQuery try using dot notation..
$(function() {
$('.link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
It's convenient to use attr method like this:
$(function() {
$('.link-active').attr('href', function(i, href) {
return href.replace('http://www.linkplus.com/xQWE=', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link-active" href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
Change your code on line 3 to
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
Full code should be
$(function() {
$('link-active').each(function() {
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
});
});
remove is not being used correctly here, as that method is meant to remove elements from the DOM and accepts a selector string as its argument.
Try something like this instead:
$(function() {
$('.link-active').each(function() {
var href = $(this).attr('href');
var strToReplace = 'http://www.linkplus.com/xQWE=';
$(this).attr('href', href.replace(strToReplace, ""));
});
});
Above we use replace to replace the start of the link with an empty string.
You have to get the string, replace it and then set it again.
Something like this:
$(function() {
$('link-active').each(function() {
replacement = 'http://www.linkplus.com/xQWE=';
url = $(this).attr('href');
$(this).attr('href', url.replace(replacement, ''));
});
});

jQuery doesn't let me use href

jquery:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
});
html:
Because of this i cant use href anymore.
I use the jqueryto show more links.
It appears that you're trying to use div's and p's like anchors (a). href is not a valid attribute of div or p.
If you're trying to store data in the div and p tags, use data-href="" in conjunction with window.open()
Based on the limited code provided, my guess is that you're trying to do something like this:
$(".container").on("click", function(e) {
e.preventDefault();
const $this = $(this);
$(".map.active").removeClass("active");
$this.siblings(".map").toggleClass("active");
let href = $this.attr("data-href");
// Open a new window
window.open(href);
// OR
// Navigate without opening new window
window.location.href = href;
});
Or, you could skip the jQuery all together an just use anchor tags as they're designed to be used.
You can use jQuery for get any attribute of elements. So if you want to use href, just do:
var new_location = $('a').attr('href');
So you can do anything by click on a tag and at the least redirect to href path by:
window.location.href = $(this).attr('href');
Note: $(this) point to current clicked a tag. So you have something like this:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
window.location.href = $(this).attr('href');
});

Transforming href links on pageload using jquery

I need to transform all the links(href values) to specific format
for example - if a page has a link http://www.exampledomain.com i want to convert its href to http://url.com/xyz?http://www.example.com
Below is the jquery i am using for this task (Note that i am new to jquery)
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
});
});
But above script is converting all the links of the website and my navigational links are also getting changed. How can we filter to change only the href's of links that contain 'http' and 'www'?
I know some kind of regex can be used for this purpose. Thanks in advance!
I thinks you should extract all internal links.
You can check if value match your criteria (http://www):
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.indexOf("http:\\www") > -1 ){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
But it will be better to extract all the internal links:
var myHost = new RegExp(location.host);
$('a').each(function(){
var value = $(this).attr('href');
if(!(myHost.test(value))){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
The last and better option is to take just the external links: ( if you don't have to do anything to the internal)
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
You could try for the following code
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.match("http://www.*"))
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});
You have to make sure that no navigation link contain
"http://www"
in them. Use relative links where you dont want to replace the href.
Or you could give a class to all anchor tags which you want to modify accordingly
Demo Fiddle
Check the anchor tag's href using element inspector
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
using window.location.host and test
Modified from this article at CSS-Tricks.com
One approach:
// selects all 'a' elements:
$('a')
// sets the 'href' attribute, using the anonymous function to iterate over each
// 'a' element:
.attr('href', function(i,oldhref){
// i: the index of the current element in the returned collection,
// oldhref: the value of the 'href' before manipulation by the function.
// if 'exampledomain.com' features in the hostname of the link we
// manipulate the 'href' as required, otherwise we simply set the 'href'
// to its original value:
return this.hostname.indexOf('exampledomain.com') > -1 ? 'www.url.com/xyz?' + oldhref : oldhref;
});
JS Fiddle demo.
References:
JavaScript:
String.prototype.indexOf().
jQuery:
attr().
You can check the link is external or internal then you can add the additional effort.
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if($(this[href^='http'])
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});

Remove the # from the variable

I have this script:
Menu item
I can not edit the html. Only the js. This is my js:
// Click
$('.next-content').click(function() {
var url = $(this).attr('href');
console.log(url);
});
When i click on the a button. I get the variable. The href in the variable. The variable is #extensive. But, how can i remove the # from the variable?
Thanks for help
var url = $(this).attr('href').substring(1);
You can replace the '#' character
url.replace('#','')
or substring
url.substring(1)
Can't you just do
// Click
$('.next-content').click(function() {
var url = $(this).attr('href');
url=url.replace("#","");
console.log(url);
});
You can google it easily...
var url = $(this).attr('href').substr(1);
I'm unsure really.
This may help. I would have said replace would have been your best option:
url.replace('#', '');

jQuery replace all href="" with onclick="window.location="

So I have a cool one for ya.
I need to scan my html document as it is rendering and replace every
href=""
with
onclick="window.location=''"
more than that, I need to carry the link from the href to the window.location.
For example, if I had:
href="http://www.google.com.au"
it would become:
onclick="window.location='http://www.google.com.au'"
and I need it to do this on every href in the document
I have no idea, but it needs to be in jQuery / javascript :D
Thanks guys.
You could try this:
$('a').each(function() {
var href = $(this).attr('href');
$(this).attr('onclick', "window.location='" + href + "'")
.removeAttr('href');
});
What are you trying to achieve with this? Chances are that there's a more elegant way to achieve what you're after.
For example, it might be better to handle the event yourself in the JS. Replace the third line with:
$(this).click(function() { window.location = href; })
That could become very expensive though, so you might want to consider jQuery's delegate events: http://api.jquery.com/delegate/
This should achieve what you want...
$('a[href]').click(function(event) {
event.preventDefault();
window.location = this.href;
});
I assume you wanted to prevent default behaviour of links.
For all possible links, you could use document.links.
For all links and future links, use event delegation.
$('body').on('click', 'a[href]', function() {
window.location = this.href;
});
Some non-jQuery variants:
Keep href:
var i = document.links.length;
while (i--)
document.links[i].onclick = function(){window.location = this.href;};
Keep href and don't follow it if onclick called (even though it goes to the same place):
var i = document.links.length;
while (i--)
document.links[i].onclick = function() {
window.location = this.href;
return false;
};
Remove href:
var i = document.links.length,
link;
while (i--) {
link = document.links[i];
link.onclick = (function(href) {
return function() {
window.location = href;
}(link.href));
link.href = '';
}
link = null;
Of course I don't understand why you want to replace a robust, works everywhere solution with an unreliable, easily broken one.

Categories

Resources