JSFiddle - React, Tailwind, and code Playground

by dshilkret

JavaScript

// Sample HTML string
var inputStr = '<div><a href="https://ven02714.service-now.com/nav_to.do?uri=incident.do?sys_id=\'<span>123</span>\'">Incident</a><br/><h3>[short_description]</h3></div>';

// Check if the string contains an <a> tag with an "href" attribute
var anchorMatch = inputStr.match(/<a\s+[^>]*href=['"]([^'"]*)['"][^>]*>/i);

if (anchorMatch) {
  // Extract the "href" attribute value
  var hrefValue = anchorMatch[1];

  // Extract content between <span> and </span>
  var spanContent = hrefValue.match(/<span>(.*?)<\/span>/);

  // If <span> tags are found, replace them with the extracted content
  if (spanContent) {
    hrefValue = hrefValue.replace(/<span>(.*?)<\/span>/, spanContent[1]);
  }

  // Forming the modified "href" attribute
  var modifiedHref = 'href="' + hrefValue + '"';

  // Replace the original "href" attribute with the modified one
  var resultString = inputStr.replace(/<a\s+[^>]*href=['"][^'"]*['"][^>]*>/i, '<a ' + modifiedHref + '>');

  console.log(resultString);
} else {
  console.log("No <a> tag with an 'href' attribute found in the string.");
}