切换无类的替换字符diactritics

问题描述 投票:0回答:1

我试图替换php字符串文本中的一些字符,这些字符没有a类,可能在页面的任何地方。

我试过这样的方法(删除 "w "字母),但它的工作原理为 pbr...等,但不能使用普通字符。 或者给它一个字符列表,让它从文本中删除,如 $("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中(文本随着页面的变化而变化).我想替换一些没有a类的php字符串文本,这些文本可能在页面的任何地方。

<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>
javascript string replace character
1个回答
1
投票

如果你至少对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;
  }  
});

© www.soinside.com 2019 - 2024. All rights reserved.