There is a variable in which such text is stored:

всем привет <h4>это я</h4> и это мой сайт: <a href="mysite.com" target="_blank">mysite.com</a> 

How can this text be made from this text:

 всем привет <h4>это я</h4> и это мой сайт: mysite.com 

that is, I need to remove the HTML link code while leaving the link text itself without affecting other HTML tags, thanks

  • @Visman there it was said only about links, and there are also other tags that need to be preserved - Pavel Mayorov
  • and why put all this in a variable and then remove the link? - Raz Galstyan

4 answers 4

I can offer such a fragment

 var element = document.getElementsByTagName("a")[0]; var parent = element.parentNode; while (element.firstChild) parent.insertBefore(element.firstChild, element); parent.removeChild(element); 
 <a href="google.com">ссылка</a> на сайт удалена 

  • It seems to work. Made not through regulars. I wonder what for minus something? - Nick Volynkin
  • Perhaps the fact is that the code works with the document , and not with an arbitrary string. - Nick Volynkin

If your html is valid in a variable, you can use a regular to remove the opening / closing tag a :

 var text = "всем привет <h4>это я</h4> и это мой сайт:\n\ <a href=\"mysite.com\" target=\"_blank\">mysite.com</a> и <a href=\"mysite2.com\" target=\"_blank\">mysite2.com</a>"; text = text.replace(/<a[^>]*>|<\/a>/ig, ''); console.log(text); 

     var s = 'всем привет <h4>это я</h4> и это мой сайт:\n\ <a href="mysite.com" target="_blank">mysite.com</a>'; $("body").html(s).find("a").replaceWith(function () { return $(this).html(); }); 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

    • Anything besides code? - Pavel Mayorov
    • @PavelMayorov, here and so everything is clear. But if you really want, you can write your own answer. - Qwertiy
    • 2
      Now on the page three answers that are not clear how different. And besides, they are shown in random order ... - Pavel Mayorov
    • @PavelMayorov, and none of them fit the author, because he wants to get a string, not dom-elements. It's time to write another one. And the random order is not scary - they are all independent and different :) - Qwertiy
    • @Qwertiy is the time to issue one normal answer - PashaPash

     var s = 'всем привет <h4>это я</h4> и это мой сайт:\n\ <a href="mysite.com" target="_blank">mysite.com</a>'; var els = $.parseHTML(s).map(function (x) { return x.tagName === 'A' ? document.createTextNode(x.textContent) : x }); $("body").append(els); 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

    • Thanks, your answer practically came to me, but the fact is that I have a function that the text enters, then the text goes into a variable, and after processing, the function returns this variable, I tried to insert your code, even played a little, I Some errors in the console, tell me how to adapt it to the function? - turik97