Jignesh Rajput
Jignesh Rajput

Reputation: 3558

replace URL into HTML Jquery

I have used static http:// url into my html(s) page, now i want to replace with empty string.

Suppose here is HTML Content:

<div id="MSO_ContentTable">
    <script type='text/javascript'> 
    function RedirectURL(RedUrl,curTab)
    {
       window.location.href='http://www.contoso.com/Sales/SitePages/'+RedUrl;
    }
    function nav2Lib(RedUrl)
    {
        NavigateHttpFolder('http://www.contoso.com/Sales/RFP%20Bank/'+h3url, '_blank');
    }
   function nav2Proposal(RedUrl)
   {
     NavigateHttpFolder('http://www.contoso.com/Sales/Proposals/'+h3url, '_blank');
   }
    </script>
  ........ lots of html contents
 </div>

Edit :

   $('#MSO_ContentTable').html().replace(/http://www.contoso.com/g,''); 

I want to replace whole url "http://www.contoso.com/" to empty string.

Upvotes: 0

Views: 515

Answers (4)

Raja Jaganathan
Raja Jaganathan

Reputation: 36197

Try this. I think you need to escape two forward slashes that's it.

$('#MSO_ContentTable').html().replace(/http:\/\/www.contoso.com/g,"");

Upvotes: 1

Faust
Faust

Reputation: 15404

The replace doesn't really need to use a regex, in your case (it's a simple replacement).

Also, in your code, you get the html from the table, perform an action on it, but then never set the resultant string back as the html of the table.

Try this:

$('#MSO_ContentTable').find([href^="http://www.contoso.com"]).each(function(){
    var href = $(this).attr('href');
    $(this).attr('href', href.replace('http://www.contoso.com', '');
});

It finds all children of the table with an href starting with http://www.contoso.com` and then replaces each href with empty string.

Upvotes: 1

developerCK
developerCK

Reputation: 4506

Your code is working,

You can check on fiddle.

var txt = $('#MSO_ContentTable').html();
alert(txt.replace(/www.contoso.com/g,''));

http://jsfiddle.net/mUMwd/

Upvotes: 0

olleicua
olleicua

Reputation: 2118

Slashes in regular expressions need to be escaped: /http:\/\/www.contoso.com/g. Alternately the replace method can take a string instead of a regular expression:

 var txt =  $('#MSO_ContentTable').html().replace('www.contoso.com','');

It's worth noting however that using a string here is technically different. It looks like in this case there is only ever going to be one replacement but if you actually want to replace every instance of the patter (as the g flag would indicate) a string will not work.

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_Searching_With_Flags

Upvotes: 1

Related Questions