1

I need to replace all <a> with <span> tag from a string .

code:

var a = input.replace(/<a>/g, "'<span>");
var b = a.replace(/<\/a>/g, "</span>");
var c = b.replace(/href/g, "title");

but it not worked for me and I could not add style as well

Input : Angular is a platform for building mobile and desktop web applications.
<a href="http://www.google.com">Test Link</a> Achieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering.
<a href="http://www.google.com">Test Link Two</a>

Output : Angular is a platform for building mobile and desktop web applications.
<span style="color:#0000EE" title="http://www.google.com">Test Link</span> Achieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering.
<span style="color:#0000EE" title="http://www.google.com">Test Link Two</span>.

can anyone help me to fix this .

1
  • 2
    You are trying to replace the string "<a>", but there is no such string, because the link also has an href attribute. Regular expressions are not the right tool to tackle HTML! Commented Oct 4, 2019 at 11:19

1 Answer 1

2

As mentioned in my comment above, regular expressions are not the right tool for tackling (i.e. parsing, modifying...) HTML. Here's an example demonstrating an approach using DOMParser() for actually replacing the link tags with a newly created span.

var inputString = `Angular is a platform for building mobile and desktop web applications.
<a href="http://www.google.com">Test Link</a> Achieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering.
<a href="http://www.google.com">Test Link Two</a>`;

var domParser = new DOMParser();
var doc = domParser.parseFromString(inputString, 'text/html');
var links = doc.querySelectorAll('a:link');
links.forEach(function(linkTag) {
  var spanTag = document.createElement('span');
  spanTag.title = linkTag.href;
  spanTag.style.color = '#0000EE';
  spanTag.innerHTML = linkTag.innerHTML;
  linkTag.parentNode.replaceChild(spanTag, linkTag);
});
console.log(doc.body.innerHTML);

Sign up to request clarification or add additional context in comments.

2 Comments

If the string has img tag that got affected while using this code , Is it possible to exclude image tag to be processed here @ConstantinGroß
The selector used in this code doesn't apply to img tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.