Trim partial link in jQuery - javascript

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, ''));
});
});

Related

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

replace matching text in hyperlink href

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/

How to find and edit a elements' href values without losing query params?

How do I find any element <a> in the page contain the href attr /dailyTickets/front/user.form.php, then change it to /dailyTickets/front/contacts.form.php?
Notice that I want to keep the URL query parameters (id) following the path (user.form.php). For example, changing this:
<a id="User_648_648" href="/dailyTickets/front/user.form.php?id=648">ConseillerUser</a>
to this:
<a id="User_648_648"href="/dailyTickets/front/contacts.form.php?id=648">ConseillerUser</a>
I'm starting with this, but I don't know how to end it:
$('a[href*="dailyTickets/front/user.form.php"]').each(function () {
if ($(this).children().length == 0) {
...........
}
});
There's no need for a loop, jQuery does that interally for you, and just using the selector outright will change any and all elements that match:
$('a[href*="dailyTickets/front/user.form.php"]').attr('href', function(i,href) {
return href.replace('user.form.php', 'contacts.form.php');
});
This will do the trick and keep all GET parametes:
$('a[href*="dailyTickets/front/user.form.php"]').attr('href', function() {
var search = '/dailyTickets/front/user.form.php', // 'user.form.php'
replace = '/dailyTickets/front/contacts.form.php'; // 'contacts.form.php'
return this.href.replace(search, replace);
});
You can use the pathname property of the Anchor for not changing host, query or hash.
$('a[href*="dailyTickets/front/user.form.php"]').each(function() {
this.pathname = "dailyTickets/front/contacts.form.php"; // don't assign to href
});
// or just
$('a[href*="dailyTickets/front/user.form.php"]').prop("pathname", "dailyTickets/front/contacts.form.php");

Append to a.href id from input field

I am trying to append to a link with id a value that is entered from the input text field. I came this far searching stackoverflow but id doesn't work!
<script type="text/javascript">
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
});
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code='.text(value);
});
});
</script>
and this is how the html looks like
<form>
<fieldset>
<input id="txt_name" type="text" value="discount" />
</fieldset>
</form>
<a id="coupon_link" href="https://www.e-junkie.com/ecom/gb.php?c=cart&i=XXXXXX&cl=YYYYYY&ejc=2" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><img src="http://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" alt="Add to Cart"/></a>
You probably meant this:
$(function() {
$("#coupon_link").on('click', function(e) {
e.preventDefault(); // apparently not needed
location.href = $(this).attr('href') + '&discount_code=' + encodeURIComponent($('#txt_name').val());
});
});
You don't have to update the value of #txt_name on keypress; you only have to use the value when the link is pressed.
Fix your code like this :
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
var link = $("#coupon_link");
var originalHref = link.attr('originalHref');
if (!originalHref) {
originalHref = link.attr("href");
link.attr("originalHref", originalHref)
}
link.attr("href", originalHref + '&discount_code='+value);
});
});
A few things to note :
never add anything to a selector when you're targeting an element by ID
your value variable wasn't in the same scope
the return of val can be directly concatenated, you don't need to try to change it to text
you don't need to pass a function to attr in your case
you're trying to make the href grow with every key stroke. This is a bad idea. The solution I propose is to keep the original href
if you're not sure the original href has yet some parameters (i.e. has '?') you should test it (I let you do that)
Overall a much cleaner solution wouldn't be to change the link but to build the href on click on the link :
$("#coupon_link").click(function(e) {
location = this.href + '&discount_code=' + $('#txt_name').val();
});
Not sure to understand, but it looks like a scope issue try this javascript :
<script type="text/javascript">
jQuery(function(){
var value = 0;
$("#txt_name").keypress(function() {
value = $("#txt_name").val();
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code=' + encodeURIComponent(value);
});
});
});
</script>
Try this:
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href", '&discount_code=' + String(value));
});
});
This isnt working because the href isnt being changed as the function is called before a keypress event is triggered. Look into replacing keypress with blur and update the href when blur() is called
i think you need this:
<script type="text/javascript">
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href",href+'&discount_code='+value.toString);
});
});
</script>
look at href don't know where you have that var, if it is needed ok else remove that
You probably need to change the href when a key has been pressed, not only on page load. To do so you will have to do the replacing of the href inside the keyup function, like so:
$(function(){
var link = $("a#coupon_link");
link.data('href', link.attr("href"));
$("#txt_name").on('keyup', function() {
link.attr("href", link.data('href') + '&discount_code='+ this.value);
});
});
So as to not append the &discount_code=*** several times, you need to store the original href somewhere, like in a data attribute.
this one worked for me getting value from input field and append it to the existing link using jquery.
$('#qty').on('keyup', function() {
var theQty = 0;
theQty = $("#qty").val();
var oldHref=$("a#buybtn").attr("href");
$("a#buybtn").attr("href",oldHref+ '&qty=' + String(theQty));
});

capture link text and append to the URL as query string

I want to capture the text that is in between anchor link tag and pass it to the href value as query string so it looks like http://mysite.com/events/Pages/default.aspx?cat=cancer
The reason I can't add that manually is because the value in between and is dynamic. How do I capture that and append to the url using jquery or javascript??
or i can maybe, at the event of Cancer link being clicked, direct it to http://mysite.com/events/Pages/default.aspx?cat=cancer
 Cancer
$("a").on("click", function (e) {
e.preventDefault();
window.location = this.href + $.trim($(this).text());
});
Or you could replace the href attribute for each link:
$("a").prop("href", function () {
return this.href += $.trim($(this).text());
});
Then clicking each link will automatically direct the user correctly. Your selector ($("a") should be more specific, depending on your markup)
Example: http://jsfiddle.net/6U749/
Edit: If you have to do it inline, here's one way:
Cancer
You could do something like this:
$('.someClassImStickingOnLinksThatNeedThisBehavior').each(function()
{
this.href = $.trim(this.href) + $.trim(this.innerHTML);
});
Then, for any link, it would automatically update the HREF to the current HREF plus the value of the node.
You can do:
var yourlink = $("#youlink");
var href = yourlink.attr("href");
var text = yourlink.html();
yourlink.attr("href", href + "?cat=" + text);

Categories

Resources