0

Basically, I'm trying to replace a part of url in the middle ('#') with another one, and remove first part of url. Script replaces '#' with no problem but rfuses to remove the first part of url. Am i doing something wrong, or is there another solution for that?

html of it

<a class="link_imagelibrary" href="#pink_yellow_flowers.pdf?5612">Download pdf set</a>

on condition changes to

<a class="imgdownload" href="http://www.picturewall.com/pages/Botanicalhttp://#.com/s/files/1/0183/2687/files/passpink_yellow_flowers.pdf?5612">Download pdf set</a>

jquery

$(".imgdownload").each(function(){ 
   this.href = this.href.replace('#', 'http://#.com/s/files/1/0183/2687/files/pass');
   this.href = this.href.replace('http://www.#.com/pages/botanical', '');
}); 

It's supposed to happen on condition. Judging that the rest of the script works fine on the condition- looks like the problem is somewhere here

user3638287
  • 43
  • 1
  • 13

2 Answers2

0

The href is expanding with this.href, so while you have:

<a href="#" ...

The DOM element's href property gets this:

<a href="http://example.com/your/page/wherever.php#" ...

The easiest way to handle this is to do it differently:

$(".imgdownload").each(function(){ 
   this.href = 'http://cdn.shopify.com/s/files/1/0183/2687/files/pass' +
               this.href.split('#').pop();
});

Here is a demonstration of the "problem":

$('a').each(function ea(){
    console.log(this.href, this.getAttribute('href'));
});

http://jsfiddle.net/Gtr8V/

You'll note that element.getAttribute('href') does return the raw href attribute value, not the property. You could use this with .replace() instead of the this.href.replace() you were trying.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • the thing is, that # splits url in 2. I need to keep the part that comes after # (pink_yellow_flowers.pdf?5612 for example), and this solution is going to edit entire url. – user3638287 May 25 '14 at 23:48
  • Unless I'm confused, looking at the code in your question, you're doing two steps, the first of which is causing the need for the second (removing the first URL). What I'm proposing is to do one thing (not two) that replaces the need to remove the first URL in a second step. – Jared Farrish May 26 '14 at 00:35
0

This line is not being matched

this.href = this.href.replace('http://www.picturewall.com/pages/botanical', '');

because it doesn't exist in your href: (Note the capitalisation of 'Botanical')

"http://www.picturewall.com/pages/Botanicalhttp://cdn.shopify.com/s/files/1/0183/2687/files/passpink_yellow_flowers.pdf?5612"
Moob
  • 14,420
  • 1
  • 34
  • 47