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&变量使一切变得简单,但它仍然不起作用。

还尝试了在HTML&oldlink变量。。仍然没有运气

如果有人能帮我做这件事,我将不胜感激,或者也许能看到我缺少什么?!

感谢

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

您可以使用此功能:

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

另请参阅此问题。

相关内容

最新更新