jetlej
jetlej

Reputation: 3392

REGEX / replace only works once

I'm using REGEX and js replace to dynamically populate a variable in a href. The following code works the first time it is used on the page, but if a different variable is passed to the function, it does not replace ANYTHING.

function change(fone){
    $("a[href^='/application']").each(function(){ 
        this.href = this.href.replace(/device=.*/,"device="+ fone);
    });
}

Upvotes: 0

Views: 260

Answers (5)

Town
Town

Reputation: 14906

As Squeegy says, you're changing the href the first time around so it no longer begins with /application - the second time around it begins with http://.

You can use the jQuery Attribute Contains Selector to get the links, and it's probably also better practice to use a capture group to do the replacement. Like so:

$("a[href*='/application']").each(function(){
     this.href = this.href.replace(/(device=)\w*/, "$1" + fone);
});

Upvotes: 1

Jamie Treworgy
Jamie Treworgy

Reputation: 24344

.href returns a fully qualified URL, e.g. `http://www.mydomain.com/application/...'. So the selector doesn't work the 2nd time around since your domain relative URL has been replaced with a full URL, and it's looking for things that start with "/application".

Use $(this).attr('href').replace... instead.

Fiddle here: http://jsfiddle.net/pcm5K/3/

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187282

The problem is that this.href actually returns a full absolute URL. So even your HTML is <a href="/foo"> the .href property will return http://mydomain.com/foo.

So your href attributes is being populated with a full absolute URL, and then the a[href^='/application'] selector doesn't match anymore, because the href attribute starts with the domain name, instead of /application.

Upvotes: 3

herostwist
herostwist

Reputation: 3968

The reason is that unless all you links start as "/device=." the regex wont work.

you need to use /.*device=.*/ 

the lack of global flag is not the problem. its the backslash in your pattern.

Upvotes: 0

gabriel
gabriel

Reputation: 1807

You'll need to add the g flag to match all instances of the pattern, so your regular expression will look like this:

/device=.*/g

and your code will look like:

this.href = this.href.replace(/device=.*/g,"device="+ fone);

Upvotes: 0

Related Questions