繁体   English   中英

Javascript:使用String.replace()替换/删除HTML锚点

[英]Javascript: using String.replace() to replace/remove HTML anchors

我正在尝试完成一项非常简单的任务,如果有一种方法可以用一个简单的字符串替换另一个。

我有一个页面的HTML源作为字符串。 它包含几个内部锚点,例如<a href="#about">,<a href="#contact">,<a href="#top">,<a href="#bottom">,<a href =“#who-we-are”>等。

所有锚点都存储在一个数组中(['about','contact'],...),我需要删除每次出现的字符串,例如

href="#whatever"

(每次都是不同的地方),结果是<a>

我将使用简单的搜索和替换操作来遍历数组并替换每次出现的

'href="'+anchorname+'"'

用空字符串。 但是经过对string.replace()的多次尝试之后,我仍然没有找到实现此目的的方法。


换句话说(也张贴在评论中):提出我的问题的简单得多的方法是:

假设我的字符串包含以下三个字符串

<a href="#contact"> <a href="#what"> <a href="#more">

如何使用Javascript用<a>替换它们(但不能替换具有相同模式的任何标签)?

All of the anchors are stored in an array (['about','contact'],...), and I need to remove every occurance of a string like href="#whatever" (where whatever is each time something different) so that the result is

为此,您可以执行以下操作:

var tets_array = $("a[href^='#']"); // select all a tags having href attr starting with #

然后使用数组并根据需要进行修改。

我不知道我是否理解这个问题,但是您可以尝试以下操作:

var index = myArray.indexOf('whatever');

myArray[index] = "whatever2"

如果我对您的理解正确,则可以使用正则表达式替换所有这些。

var tagString = '<a href="#contact"> <a href="#what"> <a href="#more">';

// Find every occurrence which starts with '#' and ends with '"'
var regEx = new RegExp('#.*?"', 'g'); 

// Replace those occurrences with '"' to remove them
tagString = tagString.replace(regEx, '"');

编辑:

要替换数组中的特定标签,可以执行以下操作:

var tags = ['<a href="#a">', '<a href="#b">', '<a href="#c">'];
var tagsToReplace = ['a', 'c'];

for (var i = 0, len = tags.length; i < len; i++) {
    var matches = tags[i].match(/#.*"/);
    if (matches === null) {
        continue;
    }

    var anchor = matches[0].substr(1).replace('"', ''); // Get only the anchor
    if (tagsToReplace.indexOf(anchor) !== -1) {
        tags[i] = tags[i].replace('#' + anchor, 'replaced');
    }
}

一种具体的陈述如下:

var mystring = '<a href="#thistag"> <a href="#thattag">';
var repstring = mystring;
var myarray = ['thistag', 'theothertag'];

for (var i = 0; i < myarray.length; i++) {
  var reptag = myarray[i];
  repstring = repstring.replace('a href="#' + reptag + '"', 'a');
}

然后repstring包含最后一个字符串。 请注意交替使用单引号和双引号字符,以确保双引号作为HTML文本的一部分位于其通常位置。 显然,您可以将reptag (即myarray的内容)更改为包含#字符,这时您将更改mystring.replace(...)行以进行匹配。

感谢您的所有建议。 我尝试了其中的各种变体,并发现其中一些在Firefox中工作,但在chrome中不工作,这导致我进入了该线程。

为什么javascript不能替换全局标志在Chrome或IE中起作用,如何解决呢?

这导致了我的解决方案:

for (var i=0; i < myTags.length ; i++)
{
        var find = 'href="#' + myTags[i] + '"';
        var regex = new RegExp(find, 'gi');
        MyWholeString = MyWholeString.replace(regex, '');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM