Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replaces all words that are not wrapped in a span tag

I’m looking for a way to replace all words not wrapped in a span tag to (space).
I’ve tried various ways, but so far not getting what I want.

The code that I wrote below is quite effective, but there are still many shortcomings.
For example if the lyrics are capitalized, they will not be converted to spaces.

So what’s the best way to achieve this goal?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the code I currently have:

Update:
On the second line, the capital letters aren’t converted to spaces, so it’s pretty messed up.

I want the result to be: Am Em C G C G

<div class="chord">

abcd ef<span>Am</span>ghi jklmn op<span>Em</span>
Yes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk
qrst<span>C</span>uvwxyz abcde<span>G</span>fghijk

</div>
$('.chord').each(function() {
    var $this = $(this);
    $this.html($this.text().replace(/a|c|d|e|f|g|h|i|j|k|l|n|o|p|q|r|s|t|u|v|w|x|y|z|<|>|\/|"|'|=|_|-|1|2|3|4|5|6|7|8|9|0/g, " ")
    .replace(/ b| m/g, "  ")
    .replace(/\[ | \]|\( | \)|\[\(|\)\]| :|\nm|\nb|\n\n/g, "\n")
    );
});

>Solution :

This code simply goes through all of the child nodes of the <div class="chord"> element and replaces text nodes with sequences of spaces of equal length to the existing string. Note this only works because the tree here is flat; a child of .chord is either a text node or a span. If either of those changes, the code will need to be more complex to accomodate.

const container = document.querySelector('.chord');
for (const kid of container.childNodes) {
  if (kid.nodeType === Node.TEXT_NODE) {
    kid.nodeValue = " ".repeat(kid.nodeValue.length);
  }
}
.chord { white-space: pre; font-family: monospace; }
<div class="chord">

abcd ef<span>Am</span>ghi jklmn op<span>Em</span>
Yes<span>C</span>uvwxyz abcDE<span>G</span>Fghijk
qrst<span>C</span>uvwxyz abcde<span>G</span>fghijk

</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading