Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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/

share|improve this question

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

share|improve this answer
1  
That will replace the entire href value, but he apparently only wants to replace the matched part. – Explosion Pills Apr 17 '13 at 4:56

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

share|improve this answer
    
As I tested, there have some problem with Unicode character such as Chinese character. – kst Apr 17 '13 at 6:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.