1

would like some help replacing a part of a string using jquery, so here is what i have:

http://www.test.com/santa-cruz-island/?iframe=true&width=60%&height=70%

i would like to replace all the content from ?iframe= up to the end:

up to now i have this:

jQuery('.islands_info_ggt').each(function() {
         url = jQuery(this).attr('href');
        _imgr = url.replace('iframe=', 'test');

    jQuery(this).attr('href', _imgr)
});

Result: http://www.test.com/santa-cruz-island/?testtrue&width=60%&height=70%

This is the result im looking for: http://www.test.com/santa-cruz-island/?test

6 Answers 6

7

Use regex replace instead:

_imgr = url.replace(/iframe=.*$/, 'test');

BTW, you don't have to wrap all these elements in jQuery: this...

jQuery('.islands_info_ggt').each(function() {
  this.href = this.href.replace(/iframe=.*$/, 'test');
});

... will give you the same result, I suppose. In fact, you can use even more concise .attr(name, function) form:

jQuery('.islands_info_ggt').attr('href', function(_, attr) {
   return attr.replace(/iframe=.*$/, 'test');
});
Sign up to request clarification or add additional context in comments.

2 Comments

or even jQuery('.islands_info_ggt').attr("href",function(attr){ return attr.replace(...
@KevinB Thanks, totally forgot about that. )
4

For a non-regex solution, You could split & then take the first element

var url = "http://www.test.com/santa-cruz-island/?iframe=true&width=60%&height=70%";
var finalurl = url.split('iframe=')[0] + "test";

result - http://www.test.com/santa-cruz-island/?test

Comments

1

Currently it is matching only 'iframe=.'. So you need .* so that it will match all the characters after it and $ to indicate the end.

url.replace('/iframe=.*$/', 'test');

Comments

1

You can use indexOf to find the location of "iframe=" in the string, get only the part of the string before that, and add whatever you want after it:

_imgr = url.substr(0, url.indexOf('iframe=')) + 'test';

Comments

0

You could use Regex:

_imgr = url.replace(/iframe=.*$/, 'test');

Comments

0

Do in code exactly what you want to do as directly as possible.

This will result in the clearest and most maintainable code.

In this case you want to take the sub string up to the location of the string of interest and add your string to it.

url = url.substr(0,url.indexOf('iframe=')-1)+'test';

Using an API like this to do exactly what you are trying to do will always make your code clearer to others who are trying to read it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.