Переключить замену символов / диакритических знаков без класса - PullRequest
0 голосов
/ 05 мая 2020

Я пытаюсь заменить некоторые символы в тексте строки php, который не имеет класса a и может находиться где угодно на странице.

Я пробовал что-то вроде этого (чтобы удалить букву «w» "), но он работает с p или br .. et c., но не с обычными символами. Или давая ему список символов для удаления из текста, например $("w|r|e").toggle();.

Текст меняется в разных местах, но все находятся в <div id="bodytext">.

<script type="text/javascript">
    $(window).load(function(){
$(document).ready(function(){
    $("button-hide2").click(function(){
        $("w").toggle();
    });
});
    });
</script>

Это кнопка скрытия:

<button-hide2 id="mybtn">Toggle</button-hide2>

А это пример из любого текста, который находится в div (текст меняется на каждой странице):

<div id="bodytext">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

1 Ответ

1 голос
/ 05 мая 2020

Вот потенциальное решение, если вы хотя бы понимаете HTML структуру, в которой может находиться текст

// Take a snapshot of the original document body
const BodyCopy = document.body.cloneNode(true);

const button = document.querySelector('#mybtn');

// Regex of text we are searching for
const textWeAreSearchingFor = new RegExp(/l|r|m/, 'ig');
// Replace them with an empty string
const replaceWith = '';
// Hang on to the original version of the HTML
const originalText = BodyCopy.querySelector('#bodytext').innerHTML;
// Manage the state on whether or not it has been toggled
let isOriginal = true;

button.addEventListener('click', () => {
  const textArea = document.querySelector('#bodytext');

  if (isOriginal) {
    const allParagraphs = document.querySelectorAll('#bodytext p');

    // Map over all of the paragraphs and replace their text
    [...allParagraphs].map(p => {
      const currentParagraphText = p.innerText;
      const updatedText = currentParagraphText.replace(textWeAreSearchingFor, replaceWith);

      p.innerText = updatedText;
    });

    isOriginal = false;
  } else {
    // Replace with original content
    textArea.innerHTML = originalText;
    isOriginal = true;
  }  
});

...