0

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/

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

That will replace the entire href value, but he apparently only wants to replace the matched part.
1

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

1 Comment

As I tested, there have some problem with Unicode character such as Chinese character.

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.