Manny Calavera
Manny Calavera

Reputation: 6873

Using jQuery to alter parameters in link

I am using jQuery 1.3.2 and I have an input field on my page that provides link to be copied, like this one: http://mydomain.com/resize.php?src=http://www.externaldomain.com/content/Uploads/everydaymail.jpg&w=533&h=400&zc=1 . I would like to use jQuery and be able to change w=533 part to w=300, for example and also the h=400 to change into h=200 . This is an image resizing script that I'm using and I want to be able to change the height and width parameters from that link in the inputbox with my desired values that are dynamic.

I am no good at regex, can anyone provide an example/suggestion ?

Thanks.

Upvotes: 0

Views: 84

Answers (3)

Tieson T.
Tieson T.

Reputation: 21191

Haven't tested this code, so caveat emptor...

Template string:

var str = "http://mydomain.com/resize.php?src=http://www.externaldomain.com/content/Uploads/everydaymail.jpg&w=XXX&h=YYY&zc=1";  

Use as needed:

str = str.replace("w=XXX", "w=your_value_here"); 
str = str.replace("h=YYY", "h=your_value_here"); 

HTH.

EDIT:

Okay, assuming dynamic variables:

var height = 42;
var width = 42;

str = str.replace( "w=XXXX", "w=" + width ); 
str = str.replace( "h=YYYY", "h=" + height ); 

Make sense?

Upvotes: 0

Samich
Samich

Reputation: 30105

It's no matter what version of jQuery will be used. All version can set element attribute values. The main point here it to use Regex to parse this value and update params or just construct link from scratch.

Here is link builder: :)

$('#build').click(function() {

    var src = $('#src').val();
    var w = $('#w').val();
    var h = $('#h').val();

    var link = "http://mydomain.com/resize.php?src=" + src + "&w=" + w + "&h=" + h + "&zc=1";

    $('#link').attr('src', link).text(link);

});

$('#replace').click(function() {

    var src = $('#src').val();
    var w = $('#w').val();
    var h = $('#h').val();

    var link = $('#link').attr('src')

    link = link.replace(/w=\d{1,4}/i, "w=" + w)
               .replace(/h=\d{1,4}/i, "h=" + w);

    $('#link').attr('src', link).text(link);

});

Code: http://jsfiddle.net/wzc8F/10/

Upvotes: 2

Manny Calavera
Manny Calavera

Reputation: 6873

I ended up using:

var newWVal = $('#inputfield').val().replace(/w=[\d\.]+&/g, 'w='+imageWidth+'&');
var newFinalVal = newWVal.replace(/h=[\d\.]+&/g, 'h='+imageHeight+'&');
$('#inputfield').val(newFinalVal);

I think the regex could be a little smarter but it also works great this way.

Thank you for your suggestions.

Upvotes: 0

Related Questions