-1

I have this string. I want to remove span having id without removing the data.

Input: var testString = "<span class="test01">Electrical drafting Scheduling tools <span id="spcc15in0os0">draftin</span><span> </span> Scheduling tools Mechanical</span>"

Expected Output:

"<span class="test01">Electrical drafting Scheduling tools draftin<span> </span> Scheduling tools Mechanical</span>"

I am new to regex. Tried few things.

Try1: testString.replace(/<\/?span\sid=[^>]*>/g, "") Result: But it is not removing the closing Tag of span

Try2: testString.replace(/(<span id=".*"(?: \w+="[^"]+")*>([^<]*)<\/span>)/gi, "") Result: it is removing span having id with data.

KushalSeth
  • 3,265
  • 1
  • 26
  • 29
  • 3
    don't use regex to parse html content – Arun P Johny May 25 '17 at 11:54
  • As @ArunPJohny has said, [**don't use regex to parse html**](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) you can, however, use jQuery, just put you html string in `$(myStringHere)` – George May 25 '17 at 11:57
  • In which environment you want to parse this string? Server/Client-side? If you have javascript available you can do it much simpler just using [innerHTML](https://www.w3schools.com/jsref/prop_html_innerhtml.asp) – ju_ May 25 '17 at 11:59

1 Answers1

0

You should not parse HTML via regex, if you don't have to. You tagged your post with jquery, so this could work out for you:

var testString = "<span class='test01'>Electrical drafting Scheduling tools <span id='spcc15in0os0'>draftin</span><span> </span> Scheduling tools Mechanical</span>";

var $element = $(testString);
$element.find("span").each(function(index) {
    var innerText= $(this).text();
    $(this).replaceWith(innerText);
});

var newString = $element.html();

console.log(newString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ju_
  • 569
  • 1
  • 4
  • 17