开发者

REGEX / replace only works once

开发者 https://www.devze.com 2023-02-21 04:38 出处:网络
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

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.hre开发者_JS百科f.replace(/device=.*/,"device="+ fone);
    });
}


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.


.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/


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);
});


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消