-3

I need to replace the flowing:

<a href="#">something</a>

withthis:

(start-a)something(end-a)

I do not master the regex well, so the regex I have its just to change all tags completely.

string.replace(/(<([^>]+)>)/ig,"(start-a)");

Whats should I change in my regex for just replacing the first tag, and the other change to replace the ending tag?

Thanks.

revo
  • 47,783
  • 14
  • 74
  • 117
domoindal
  • 1,513
  • 2
  • 17
  • 33

1 Answers1

1
  1. Find all the tags you wish to replace.
  2. Create a new text node based on each tag.
  3. Insert new node.
  4. Delete old tag.

// Find all tags to be replaced and put in an Array and loop through them
var tags = Array.prototype.slice.call(document.querySelectorAll("a")).forEach(function(tag){
  // Find the parent element of the node
  var parent = tag.parentNode;
  
  // Create a new text node with the contents of the current element
  var replaceString = document.createTextNode("(start-a)" + tag.textContent + "(end-a)");
  
  // Insert the new text node where the current tag is
  parent.insertBefore(replaceString, tag);
  
  // Delete the old tag
  parent.removeChild(tag);
});
<div>
  <a href="#">something</a>
  <a href="#">something</a>
  <a href="#">something</a>
  <a href="#">something</a>
  <a href="#">something</a>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71