删除所有出现的href标签并将文本保留在里面

时间:2018-11-19 10:53:05

标签: javascript

我有一个包含HTML文档的长字符串。我想删除所有href标签,但保留文本。以下示例:

ELISP> (make-frame '((top . 100) (left . 100) (width . 100) (height . 30)))
#<frame Emacs 0x111ca8c00>
ELISP> (make-frame '((top . 50) (left . 50) (width . 100) (height . 10)))
#<frame Emacs 0x115a5ed50>
ELISP> (make-frame '((top . 100) (left . 100) (width . 100) (height . 10)))
#<frame Emacs 0x1116e77a0>
ELISP> (make-frame '((top . 150) (left . 150) (width . 100) (height . 10)))
#<frame Emacs 0x111ac5aa0>
ELISP> (make-frame '((top . 200) (left . 200) (width . 100) (height . 10)))
#<frame Emacs 0x115c32e00>

应成为:

Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text 

我发现的解决方案是获取所有文本,然后尝试再次遍历文本并将标记号n替换为文本号n。

Some text example 1 </p> some example 2 text 

有没有办法做到这一点?

5 个答案:

答案 0 :(得分:0)

您可以使用以下正则表达式:

var regex = /(<\s*a([^>]+)>|<\/\s*a\s*>)/ig;
var str = 'Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text';

str.replace(regex, "");  //Some text example 1</p> some  example 2text

答案 1 :(得分:0)

在第一行之后编写以下代码

a_string = a_string.replace(/(<a.*?>)/g,'').replace(/<\/a>/g,' ');

答案 2 :(得分:0)

尝试以下正则表达式:

var a_txt = a_string.replace(/<a[\s]+[^>]*?href[\s]?=[\s\"\']*(.*?)[\"\']*.*?>/g,"").replace(/<\/a>/g," ");

答案 3 :(得分:0)

您的查询选择所有a-tag的解决方案实际上还不错。除了获取带有地图的文本外,您还可以遍历列表并将每个元素替换为其内容。无需正则表达式:

el.querySelectorAll('a').forEach(function( a_el ){
    var text = document.createTextNode(a_el.innerText);
    a_el.parentNode.replaceChild(text, a_el);
});

此外,您可以使用DomParser来代替通过将其放入p元素来“解析”您的html:

var parser = new DOMParser();
var doc = parser.parseFromString(a_string, "text/html");

doc.querySelectorAll('a').forEach(function( a_el ){
    var text = document.createTextNode(a_el.innerText);
    a_el.parentNode.replaceChild(text, a_el);
});

答案 4 :(得分:0)

如上面的一些回答所述,您的代码还不错。避免在不必要时使用正则表达式。 要完成代码,您需要遍历所有A {ELEMENTS}。我正在用手机打字。如果您遇到错误,请告诉我。谢谢。

var a_string = 'Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text',

el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');

for( var t = a.length - 1; t >=0 ; t-- ){
   for(var c = a[t].childNodes.length - 1; c >= 0; c-- ){
       if( a[t].nextSibling ){
           document.insertBefore( a[t].childNodes[c], a[t].nextSibling  );
        } else {
     a[t].parentNode.appendChild( a[t].childNodes[c]);
        }
   }
   a[t].remove();
}