简体   繁体   中英

javascript string replace with RegExp

I got a problem with javascript RegExp. I want to replace the a.href with textbox value when I click on the button.But, I don't want to replace the whole string just want to find and replace those are exact match with my RegExp. Here is my code

$(document).ready(function(){
    $('#btnRun').click(function(){
        var str = encodeURIComponent($('#mydata').val());
        var regExp = new RegExp('\\b' +encodeURIComponent( $('a').html()) + '\\b','gi');
        $('a').attr('href',$('a').attr('href').replace(regExp,str));
    });
});

this is my test code http://jsfiddle.net/4uAp5/1/

Don't think you need a regex to do that. This code should accomplish what you are describing:

$('a').attr('href',$("#mydata").val());

Also worth noting is that the way you are targeting the link – $('a') – will select every link on the page...

\\\\b does not match because the href value is encoded and results (in this specific example) in cMyTest1 . c does not satisfy \\\\b . There are a variety of solutions depending upon specific circumstances. One is to use decodeURI on the href first before using the regex and then encode it later (although it's probably not needed).

http://jsfiddle.net/4uAp5/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM