0

I'm trying to remove a wrapper around a button using RegExr, but it returns a null value.

I used the solution of this question, like so:

var title = $( ".redButton" ).text();
var myString = $( "#content" ).html();
var myRegexp = /(<p>\s<button class"redButton">)((?:\s|.{1,50})*)(<.button>\s<.p>)/g;
var match = myRegexp.exec(myString);

console.log(match);

so i can eventually turn this:

<article id="content">
    <p>
        <button class="redButton">EEN HELE LANG TITEL IN EEN KNOP</button>
    </p>
</article>

into this:

<article id="content">
        <button class="redButton">LONG TITLE IN A BUTTON</button>
</article>

Before I continued I wanted to check if the RegEx worked, which it apparently doesn't. This solution would fix the problem, using escapes, but I don't understand when I should and when I shouldn't escape.

Can anyone help?

finner10
  • 43
  • 1
  • 8
  • 3
    Rule 1, do not use regex to parse HTML... rule 2, if you really need to parse HTML with regex see rule 1 – freefaller Oct 24 '18 at 08:56
  • 2
    you're using JavaScript, so just use the DOM to interact with the HTML. Regex is a terrible solution for this kind of problem. – ADyson Oct 24 '18 at 08:59
  • Possible duplicate of [How to remove only the parent element and not its child elements in JavaScript?](https://stackoverflow.com/questions/170004/how-to-remove-only-the-parent-element-and-not-its-child-elements-in-javascript) – Ivar Oct 24 '18 at 09:11

2 Answers2

1

Regular expressions and HTML generally don't work well together. Why not use DOMParser instead? Parse the string into a document, append the button to the article, then remove the p:

const htmlStr = `<article id="content">
    <p>
        <button class="redButton">EEN HELE LANG TITEL IN EEN KNOP</button>
    </p>
</article>`;
const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
const button = doc.querySelector('.redButton');
const parentToRemove = button.parentElement;
const ancestorToAppendTo = parentToRemove.parentElement;
ancestorToAppendTo.appendChild(button);
parentToRemove.remove();
console.log(doc.body.innerHTML);

This will append the button to it's parent's parent, and remove it's parent from the HTML.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

If you simply want to remove the immediate parents of an element use the jQuery method unwrap. Run the snippet then inspect the button in devtools and you'll see the paragraph tags have been removed.

const $button = $('#content .redButton');
$button.unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article id="content">
  <p>
    <button class="redButton">EEN HELE LANG TITEL IN EEN KNOP</button>
  </p>
</article>
Andy
  • 61,948
  • 13
  • 68
  • 95