1

Hoping someone can help me it's driving me nuts.

I am using SPServices and Javascript to rewrite some links after a small content migration.

I have some HTML in a variable and I'm trying to find a string which is a specific URL and replace it with a different URL. This works:

newHTML = newHTML.replace("http://urlhere/subsite/page.aspx",newLink);

Also this works:

newHTML = newHTML.replace(new RegExp("http://urlhere/subsite/page.aspx", 'gi'), newLink); 

But if I have a variable containing the same string in there it doesn't work:

newHTML = newHTML.replace(new RegExp(oldLink, 'gi'), newLink); 

My oldLink variable comes from an SPServices call to another list column containing HTML, which I take the 'a' tags and put them into an array:

function rewriteLinks() {
var urlStart = "http://urlstart";



var linkContainerArray = [];


    var theContent = $('.htmlContentDiv').html();

    // get a tags
    var aTags = ('a',theContent);
    //loop through A tags and get oldLink and Text
    $(aTags).each(function(){

    var ID;

    var itemTitle = $(this).text();

    var oldLink = $(this).attr('href');

    var newLink;

    if(itemTitle.length > 2){
        //SpService call to get ID of that item using inner text as query to SharePoint list

            $().SPServices({
            operation: "GetListItems",
            async: false,
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>",
            CAMLQuery: '<Query><Where><Eq><FieldRef Name="Title" /><Value Type="Text"><![CDATA['+itemTitle+']]></Value></Eq></Where></Query>',
            listName: 'AGItems',
            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    ID = $(this).attr("ows_ID");  
                     //Now have oldLink and newID in variables - build newLink from known URL & newID
                     newLink = urlStart+ID;     
                        });//response xml
                    }//completefunc
                });//spservices 
    //check for empty links
    if((oldLink && newLink != '') && (oldLink && newLink != undefined)){
        var linkPair = [oldLink,newLink];
        linkContainerArray.push(linkPair);
    }


    }  

   });

    replaceLinks(linkContainerArray);   


}

Then I call a function to find and replace the links (this is where my variable won't work). I've tried escaping in all combinations of the following ways:

function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[\/\\^$*+?.|[\]{}]/g, '\\$&');
}

function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery     automatically        encodes)
  //then grab the encoded contents back out.  The div never exists on the     page.
  return $('<div/>').text(value).html();
}

function htmlEscape(str) {
return String(str)
    .replace(/"/g, '&quot;')
    .replace(/'/g, "&#39;")
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
 }

 function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[\/\\^$*+?.|[\]{}]/g, '\\$&');
}

Also removed full stops and question marks from the HTML & variable to make everything simple and it's still not working.

Also tried encodeURIComponent on the HTML & oldlink variable.. still no luck

If anyone has any help for me with this at all it would be much appreciated or can maybe see what I'm missing?!

Thanks

cptasker
  • 47
  • 8
  • Could you post an example value of oldLink? Here is a fiddle that uses a variable in a regex and works: https://jsfiddle.net/omerts/rcm65bqo/ – omerts Jun 02 '16 at 09:03
  • Sure! Thanks.. oldLink is very similar to the following (after removing . and ?) also encoding the : to match what the HTML pulled from SharePoint has http://someplaintext/pages/GuidelinesaspxiPageId=14495 – cptasker Jun 02 '16 at 09:21
  • Please would you clearly define inputs and expected outputs to avoid guesswork. – 1983 Jun 02 '16 at 09:34

1 Answers1

1

It does not work because some the characters in the string have a special meaning in a regular expression, like \ and .. So they need to be escaped.

You can use this function:

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}


var newHTML = '<a href="http://someplaintext/pages/GuidelinesaspxiPageId=14495"> my link </a>';
var oldLink = 'http://someplaintext/pages/GuidelinesaspxiPageId=14495';
var newLink = 'http://urlstart?id=14495';
newHTML = newHTML.replace(new RegExp(escapeRegExp(oldLink), 'gi'), newLink); 
console.log(newHTML);

See also this question.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286