Replace part of an HREF attribute in a link with jQuery
Asked Answered
C

4

8

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?

Carver answered 16/10, 2010 at 6:23 Comment(1)
$(function() is shortcode for the latterTrellas
S
27
$(document).ready(function(){
    $('a').each(function(){
        this.href = this.href.replace('s1600-h', 's1600');
    });
});
Suellen answered 16/10, 2010 at 6:26 Comment(0)
B
2
jQuery(document).ready(function() {
  jQuery('a').each(function(){
     this.href = this.href.replace('s1600-h', 's1600');
  }); 
});
Bipack answered 31/5, 2017 at 8:29 Comment(0)
B
1

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.

Balsamic answered 25/4, 2017 at 22:28 Comment(0)
I
-2
var _authorLinkHref = $(this).find('a.temp_form').attr('href',$(this).find('a.temp_form').attr('href').replace('http://', '')); 
Irmine answered 22/10, 2013 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.