Jon
Jon

Reputation: 81

Replace part of an HREF attribute in a link with jQuery

I'm new to jQuery and I need to replace a part of an A HREF attribute in a link. More specifically, a piece of code that will remove the "-h" from "s1600-h" for a lightbox application:

In other words, turn s1600-h to s1600

Also, do I need to use $(function() or $(document).ready(function() before the piece of code?

Upvotes: 8

Views: 20153

Answers (4)

RichestSoft
RichestSoft

Reputation: 156

jQuery(document).ready(function() {
  jQuery('a').each(function(){
     this.href = this.href.replace('s1600-h', 's1600');
  }); 
});

Upvotes: 2

Ernest Correale
Ernest Correale

Reputation: 516

I know this post is old as dirt but, I, being a total noob, was banging my head over a way to change a URL parameter value in a page rendered by SharePoint. Many of the answers I found were cryptic jquery one-liners that read like Charley Brown's teacher speaks......

Using jquery-3.2.0, and some insight from Bang Dao's post, I yielded this hard fought gem.

Situation The URL containing the parameter I need to change:

<a class="ms-subtleLink" onclick="GoToLinkOrDialogNewWindow(this);return false;" href="/Site/SubSite/_layouts/15/userdisp.aspx?ID=27">UserName Text</a>

Problem I needed to change the ID parameter from 27 to 33 in every location on the page.

Solution
$('a.ms-subtleLink').attr('href',function(){this.href = this.href.replace('?ID=27','?ID=33')});

I realize I did not need to include '?ID=' as part of the replace string. I only included it to improve the degree of specificity in my match string.

I hope this helps someone with a similar issue some day.

Upvotes: 1

Jimit
Jimit

Reputation: 1

var _authorLinkHref = $(this).find('a.temp_form').attr('href',$(this).find('a.temp_form').attr('href').replace('http://', '')); 

Upvotes: -2

Bang Dao
Bang Dao

Reputation: 5102

$(document).ready(function(){
    $('a').each(function(){
        this.href = this.href.replace('s1600-h', 's1600');
    });
});

Upvotes: 27

Related Questions