Javascript查找和替换使用字符串但不是变量

时间:2016-06-02 08:52:24

标签: javascript

希望有人可以帮助我,这让我疯狂。

我使用SPServices和Javascript在一次小内容迁移后重写一些链接。

我在变量中有一些HTML,我正在尝试找到一个特定URL的字符串,并用不同的URL替换它。这有效:

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

这也有效:

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

但是如果我有一个包含相同字符串的变量,那么它就不起作用了:

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

我的oldLink变量来自对包含HTML的另一个列表列的SPServices调用,我使用'a'标记并将它们放入数组中:

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);   


}

然后我调用一个函数来查找和替换链接(这是我的变量不起作用的地方)。我尝试了以下几种方式的转义:

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, '\\$&');
}

还从HTML&amp;中删除了句号和问号。变量使一切变得简单,但仍然无法正常工作。

还在HTML&amp;上尝试了encodeURIComponent。 oldlink变量..仍然没有运气

如果有人对我有任何帮助,我会非常感激,或者可能会看到我缺少的东西?!

由于

1 个答案:

答案 0 :(得分:1)

它不起作用,因为字符串中的某些字符在正则表达式中具有特殊含义,例如\.。所以他们需要逃脱。

您可以使用此功能:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

另见this question

相关问题