1

Using the javascript replace method, I want to find this string:

<span class="memberX"><span class="member19">text</span></span>    <---X is any number

final output should be:

<span class="member19">text</span>

Essentially I want to remove the outer span which can have a class of memberX, where X is any number.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
Chad Caldwell
  • 274
  • 2
  • 12
  • 2
    [Regex should not be used to do anything that includes HTML](http://stackoverflow.com/questions/1732348) – F.P Nov 15 '12 at 20:36
  • Do you mean you have an input string containing html that includes that particular text, or do you want to find these elements on the current page? – nnnnnn Nov 15 '12 at 20:36
  • 3
    use DOM manipulation functions, not regular expressions. – jbabey Nov 15 '12 at 20:37

2 Answers2

3

If this is in the DOM, you don't want regex. You should just manipulate the DOM itself.

var spans = document.querySelectorAll('span[class^=member] > span[class^=member]');

for (var i = 0; i < spans.length; i++) {
    spans[i].parentNode.parentNode.insertBefore(spans[i], spans[i].parentNode);
    spans[i].parentNode.removeChild(spans[i].nextSibling);
}
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • 1
    +1 /me suggests DOM walking, other answerer comes with `querySelectorAll`, mind blown. :D – Tamara Wijsman Nov 15 '12 at 20:40
  • 1
    +1. Just before seeing your answer I was thinking about how easy it would be with jQuery with the same selector you used: `​$('span[class​​​​​​​​​​​​^="member​​​​​​​​"] > span[class^="member"]').unwrap();`. Nice answer. – nnnnnn Nov 15 '12 at 20:45
  • nnnnnn, I like your answer. One question, how would I achieve this if I'm not manipulating the DOM directly but passed a block of HTML content in a variable? I then have to manipulate the variable and set the new value to itself? – Chad Caldwell Nov 15 '12 at 21:10
  • @Chad: `var div = document.createElement("div"); div.innerHTML = myhtml;` Then use `div` as the root instead of `document`. – I Hate Lazy Nov 15 '12 at 21:17
0
  1. Read RegEx match open tags except XHTML self-contained tags first.

  2. Read up on the Document Object Model (in short DOM).

  3. Use the DOM functions that JS provides to walk the DOM tree.

  4. Write a traversal algorithm that walks over the DOM tree.

  5. For each span element you come across, check if it has a single child which is also a span. If that's the case, you should replace the parent span by the child span if it fits your case.

Community
  • 1
  • 1
Tamara Wijsman
  • 12,198
  • 8
  • 53
  • 82