Home > Blockchain >  Replaces all words that are not wrapped in a span tag
Replaces all words that are not wrapped in a span tag

Time:12-01

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?

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 >

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")
    );
});

CodePudding user response:

This code simply goes through all of the child nodes of the <div > 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 >

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>

CodePudding user response:

I've tried to get what you want in array check this:

const chord = document.querySelector('.chord');
const span = chord.querySelectorAll('span');
const spanText = [];
span.forEach((item) => {
  spanText.push(item.innerText);
});
console.log(spanText);
<div >

  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>

  • Related