.replace() 不会替换每个实例,尽管使用了 /g。

huangapple go评论110阅读模式
英文:

.replace() won't replace every instance despite /g

问题

我有两个问题与我的JavaScript代码有关。我将尽量保持简洁,只复制与问题有关的部分。

我有以下HTML代码(每个

  • 看起来都不同,这不是我的错):

    	<li>
    		<span style="font-family:arial, helvetica, sans-serif">Siehe <a href="Link 1" rel="">Text 1</a>.</span>
    	</li>
    	<li>
    		<span style="font-family:arial, helvetica, sans-serif">Siehe</span> <a href="Link 1" rel="">Text 2</a>.<span style="font-family:arial, helvetica, sans-serif"> </span>
    	</li>
    	<li>
    		Siehe <a href="Link 1" rel="">Text 3</a>.
    	</li>
    

    以下是我问题所需的JavaScript代码。首先,我删除了每个元素。然后,我想替换"a href"部分并增加新字符串的编号。

    var neu = document.getElementById("ausgabe").value;
    var nummer = 0;
    
    function getNextDlcNumber() {
        return ++nummer;
    }
    
    var ersetzen = neu
        .replace(/<span.*?>(.*?)<\/span>/g, "$1") // 去除所有span
        .replace(/\s<li>\n\s\sSiehe\s*<a href=".*?" rel="">(.*?)<\/a>.\n\s<\/li>/g, "\t<li>\n\t\tSiehe <a class=\"trophiesAnkerLink\" href=\"#dlc\" + getNextDlcNumber() + "\"\" rel=\"\">$1</a>.\n\t</li>")); // 用递增的dlc编号替换a href
    
    document.getElementById("ausgabe").value = ersetzen;
    

    这里有两个问题:

    1. 第一个和第三个"a href"已成功替换,但第二个没有替换,我无法弄清原因。我认为这与"Siehe"和"a"标签开始之间的span标签有关,但是由于第一个替换应该删除span,所以我不确定这是否是问题的原因。我尝试使用"Siehe\s*<a"、"Siehe <a"以及包含""的"|",但都没有成功。

    2. "#dlc"后面的数字没有递增,即使是第三个也只是"#dlc1"。我需要以不同的方式做吗?

    这是使用JS后的输出:

    	<li>
    		Siehe <a class="trophiesAnkerLink" href="#dlc1" rel="">Text 1</a>.
    	</li>
    	<li>
    		Siehe <a href="Link 1" rel="">Text 2</a>. 
    	</li>
    	<li>
    		Siehe <a class="trophiesAnkerLink" href="#dlc1" rel="">Text 3</a>.
    	</li>
    

    希望我提供了足够的信息。如果不够,我可以提供更多。先谢谢你的帮助 .replace() 不会替换每个实例,尽管使用了 /g。

    英文:

    So, I've got two problems with my javascript code. I'll try to make it as short as possible and only copy parts that are necessary for the problem.

    I have this html code (it's not my fault that every li looks different):

    	&lt;li&gt;
    		&lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 1&lt;/a&gt;.&lt;/span&gt;
    	&lt;/li&gt;
    	&lt;li&gt;
    		&lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe&lt;/span&gt; &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 2&lt;/a&gt;.&lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt; &lt;/span&gt;
    	&lt;/li&gt;
    	&lt;li&gt;
    		Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 3&lt;/a&gt;.
    	&lt;/li&gt;
    

    And here comes the necessary javascript code for my problems. First, I delete every span element. After that I want to replace the "a href" parts and increase the number of the new string.

    var neu = document.getElementById(&quot;ausgabe&quot;).value;				
    var nummer = 0;
    function getNextDlcNumber() {
    	return ++nummer;
    }
    
    var ersetzen = neu
    .replace(/&lt;span.*?&gt;(.*?)&lt;\/span&gt;/g, &quot;$1&quot;) // Gets rid of every span
    .replace(/\s&lt;li&gt;\n\s\sSiehe\s*&lt;a href=&quot;.*?&quot; rel=&quot;&quot;&gt;(.*?)&lt;\/a&gt;\.\n\s&lt;\/li&gt;/g, &quot;\t&lt;li&gt;\n\t\tSiehe &lt;a class=\&quot;trophiesAnkerLink\&quot; href=\&quot;#dlc&quot; + getNextDlcNumber() + &quot;\&quot; rel=\&quot;\&quot;&gt;$1&lt;/a&gt;.\n\t&lt;/li&gt;&quot;)); // Replaces a href with increasing dlc numbers
    
    document.getElementById(&quot;ausgabe&quot;).value = ersetzen;
    

    There are two problems with this:

    1. The first and third "a href" are replaced successfully. But the second one isn't and I can't figure out why. I think it has something to do with the span tag between "Siehe" and the start of the "a" tag, however the span should get deleted due to the first replace so I'm not sure if that's what causes the problem. I tried using "Siehe\s*<a", "Siehe <a" as well as an or using | that contained the "&lt;/span&gt;" but none of that worked.

    2. The number after "#dlc" isn't increasing, it just stays at "#dlc1" even for the third one. Do I need to do that in a different way?

    Here's the output after using the js:

    	&lt;li&gt;
    		Siehe &lt;a class=&quot;trophiesAnkerLink&quot; href=&quot;#dlc1&quot; rel=&quot;&quot;&gt;Text 1&lt;/a&gt;.
    	&lt;/li&gt;
    	&lt;li&gt;
    		Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 2&lt;/a&gt;. 
    	&lt;/li&gt;
    	&lt;li&gt;
    		Siehe &lt;a class=&quot;trophiesAnkerLink&quot; href=&quot;#dlc1&quot; rel=&quot;&quot;&gt;Text 3&lt;/a&gt;.
    	&lt;/li&gt;
    

    I hope I posted every necessary information. If not, I can provide more. Thanks for your help in advance .replace() 不会替换每个实例,尽管使用了 /g。

    答案1

    得分: 2

    以下是翻译好的内容:

    实际上,手动解析和编辑DOM元素内容是一个非常不好的主意,你不必让生活变得复杂并重新发明轮子。

    您可以使用JavaScript内置方法直接访问链接元素的.href属性,并直接更改它,甚至不使用.replace()方法。

    这是您的代码示例:

    let elements = Array.from(document.getElementById("ausgabe").querySelectorAll("a"));
    elements.forEach(a => a.href = "#dlc" + getNextDlcNumber());
    

    您可以看到,这可以只是一行代码,实现您试图达到的一切目标。

    演示:

    <div id="ausgabe">
      <li>
        <span style="font-family:arial, helvetica, sans-serif;">Siehe <a href="Link 1" rel="">Text 1</a>.</span>
      </li>
      <li>
        <span style="font-family:arial, helvetica, sans-serif;">Siehe</span> <a href="Link 1" rel="">Text 2</a><span style="font-family:arial, helvetica, sans-serif;"> </span>
      </li>
      <li>
        Siehe <a href="Link 1" rel="">Text 3</a>.
      </li>
    </div>
    

    当悬停在链接上时,您可以检查links的新值,et voilà。

    英文:

    Actually it's a very bad idea to manually parse and edit DOM elements contents, you don't have to complicate your life and reinvent the wheel.

    You can use JS built-in methods to directly access .href attribute of your link elements and change it directly, without even using .replace() method.

    This is how can be your code:

    let elements = Array.from(document.getElementById(&quot;ausgabe&quot;).querySelectorAll(&quot;a&quot;))
    elements.forEach(a =&gt; a.href = &quot;#dlc&quot; + getNextDlcNumber());
    

    You can see it can just be a one liner code, to do all what you were trying to achieve.

    Demo:

    <!-- begin snippet: js hide: true console: true babel: false -->

    <!-- language: lang-js -->

    var nummer = 0;
    
    function getNextDlcNumber() {
      return ++nummer;
    }
    
    Array.from(document.getElementById(&quot;ausgabe&quot;).querySelectorAll(&quot;a&quot;)).forEach(a =&gt; a.href = &quot;#dlc&quot; + getNextDlcNumber());
    

    <!-- language: lang-html -->

    &lt;div id=&quot;ausgabe&quot;&gt;
      &lt;li&gt;
        &lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 1&lt;/a&gt;.&lt;/span&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe&lt;/span&gt; &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 2&lt;/a&gt;.&lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt; &lt;/span&gt;
      &lt;/li&gt;
      &lt;li&gt;
        Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 3&lt;/a&gt;.
      &lt;/li&gt;
    
    &lt;/div&gt;
    

    <!-- end snippet -->

    You can check the new values of your linksby hovering them, et voilà.

    答案2

    得分: 1

    代码部分不需要翻译,以下是代码之外的内容的中文翻译:

    如其他人在评论和回答中所述,使用DOM来解析textarea中的值更容易生成所需的输出。以下是两个版本(DOM解析和文本解析),以便您可以比较使用DOM解析与文本解析的简便性。

    (这两个代码版本都可以重写和精简。它们写得详细是为了更容易调试样本。)

    DOM解析版本:

    <textarea id="ausgabe" rows="10" cols="50"></textarea>
    <textarea id="ausgabe-result" rows="10" cols="50"></textarea>
    <div>
      <button id="parse-textarea-dom">DOM解析</button>
    </div>
    <ul id="ausgabe-list-dom"></ul>
    

    文本解析版本,生成相同的输出:

    <textarea id="ausgabe" rows="10" cols="50"></textarea>
    <textarea id="ausgabe-result" rows="10" cols="50"></textarea>
    <div>
      <button id="parse-textarea-text">文本解析</button>
    </div>
    <ul id="ausgabe-list-text"></ul>
    

    请注意,这些代码中包含了HTML和JavaScript的示例,用于演示DOM解析和文本解析的不同方法。

    英文:

    As others have stated in comments and answers, using the DOM to parse the value in the textarea is much easier to generate the output you want. Below are two versions (DOM and text parsing) so that you can compare the simplicity of using DOM parsing versus text parsing.

    (Both code versions can be rewritten and condensed. They are verbose to make the samples easier to debug.)

    DOM parsing version:

    <!-- begin snippet: js hide: false console: true babel: false -->

    <!-- language: lang-js -->

    document.querySelector(&quot;#parse-textarea-dom&quot;).addEventListener(&quot;click&quot;, parseDom);
    
    const inputHtml = `&lt;li&gt;
            &lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 1&lt;/a&gt;.&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
            &lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe&lt;/span&gt; &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 2&lt;/a&gt;.&lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt; &lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
            Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 3&lt;/a&gt;.
        &lt;/li&gt;`;
    
    document.querySelector(&quot;#ausgabe&quot;).textContent = inputHtml;
    
    let number = 0;
    
    function getNextDlcNumber() {
      return ++number;
    }
    
    function parseDom() {
      number = 0;
      const neu = document.getElementById(&quot;ausgabe&quot;).value;
      const ulElem = document.createElement(&quot;ul&quot;);
      ulElem.innerHTML = neu;
      ulElem.querySelectorAll(&quot;li&quot;).forEach(liElem =&gt; {
        getNextDlcNumber();
        const anchElem = liElem.querySelector(&quot;a&quot;);
        anchElem.href = `#dlc${number}`;
        anchElem.className = &quot;trophiesAnkerLink&quot;;
        liElem.removeChild(liElem.firstElementChild);
        liElem.textContent = &quot;Siehe &quot;;
        liElem.appendChild(anchElem);
      });
      document.getElementById(&quot;ausgabe-list-dom&quot;).appendChild(ulElem);
      document.getElementById(&quot;ausgabe-list-dom&quot;).scrollIntoView();
      document.getElementById(&quot;ausgabe-result&quot;).value = ulElem.innerHTML;
    }
    

    <!-- language: lang-html -->

    &lt;textarea id=&quot;ausgabe&quot; rows=&quot;10&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
    &lt;textarea id=&quot;ausgabe-result&quot; rows=&quot;10&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
    &lt;div&gt;
      &lt;button id=&quot;parse-textarea-dom&quot;&gt;DOM Parse&lt;/button&gt;
    &lt;/div&gt;
    &lt;ul id=&quot;ausgabe-list-dom&quot;&gt;&lt;/ul&gt;
    

    <!-- end snippet -->

    The text parsing version for the same output:

    <!-- begin snippet: js hide: false console: true babel: false -->

    <!-- language: lang-js -->

    document.querySelector(&quot;#parse-textarea-text&quot;).addEventListener(&quot;click&quot;, parseText);
    
    const inputHtml = `&lt;li&gt;
            &lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 1&lt;/a&gt;.&lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
            &lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt;Siehe&lt;/span&gt; &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 2&lt;/a&gt;.&lt;span style=&quot;font-family:arial, helvetica, sans-serif;&quot;&gt; &lt;/span&gt;
        &lt;/li&gt;
        &lt;li&gt;
            Siehe &lt;a href=&quot;Link 1&quot; rel=&quot;&quot;&gt;Text 3&lt;/a&gt;.
        &lt;/li&gt;`;
    
    document.querySelector(&quot;#ausgabe&quot;).textContent = inputHtml;
    
    // stackoverflow.com/questions/31412765/regex-to-remove-white-spaces-blank-lines-and-final-line-break-in-javascript
    function condenseHTML(html) {
      return html.split(&#39;\n&#39;)
        .map(s =&gt; {
          return s.replace(/^\s*|\s*$/g, &quot;&quot;);
        })
        .filter(x =&gt; {
          return x;
        })
        .join(&quot;&quot;);
    }
    
    function getStringBetween(str, start, end) {
      const result = str.match(new RegExp(start + &quot;(.*)&quot; + end));
      return Array.isArray(result) &amp;&amp; result.length &gt; 1 ? result[1] : &quot;&quot;;
    }
    
    let number = 0;
    
    function getNextDlcNumber() {
      return ++number;
    }
    
    function parseText() {
      number = 0;
      const neu = document.getElementById(&quot;ausgabe&quot;).value;
    
      const condensed = condenseHTML(neu);
    
      // Remove every &lt;span&gt; element
      const spanRemoved = condensed.replace(/&lt;span.*?&gt;(.*?)&lt;\/span&gt;/g, &quot;$1&quot;);
    
      const pattern = /&lt;li&gt;(.*?)&lt;\/li&gt;/gi;
    
      const ersetzen = spanRemoved.replace(pattern, (li) =&gt; {
        getNextDlcNumber();
        const anchor = li.match(/&lt;a href=&quot;.*?&quot; rel=&quot;&quot;&gt;(.*?)&lt;\/a&gt;/gs);
        const anchorText = Array.isArray(anchor) ?
          getStringBetween(anchor[0], &#39;\&gt;&#39;, &#39;\&lt;&#39;) : &quot;&quot;;
        const replaceStr = `&lt;li&gt;
        Siehe &lt;a class=&quot;trophiesAnkerLink&quot; href=&quot;#dlc${number}&quot; rel=&quot;&quot;&gt;${anchorText}&lt;/a&gt;.
    &lt;/li&gt;`;
        return replaceStr + &quot;\n&quot;;
      });
    
      document.getElementById(&quot;ausgabe-list-text&quot;).innerHTML = ersetzen;
      document.getElementById(&quot;ausgabe-list-text&quot;).scrollIntoView();
      document.getElementById(&quot;ausgabe-result&quot;).value = ersetzen;
    }
    

    <!-- language: lang-html -->

    &lt;textarea id=&quot;ausgabe&quot; rows=&quot;10&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
    &lt;textarea id=&quot;ausgabe-result&quot; rows=&quot;10&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
    &lt;div&gt;
      &lt;button id=&quot;parse-textarea-text&quot;&gt;Text Parse&lt;/button&gt;
    &lt;/div&gt;
    &lt;ul id=&quot;ausgabe-list-text&quot;&gt;&lt;/ul&gt;
    

    <!-- end snippet -->

    答案3

    得分: 0

    尝试使用 neu.replaceAll(pattern, replacement)

    文档链接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

    英文:

    Try using neu.replaceAll(pattern, replacement).

    Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

  • huangapple
    • 本文由 发表于 2023年3月9日 19:51:59
    • 转载请务必保留本文链接:https://go.coder-hub.com/75684230.html
    匿名

    发表评论

    匿名网友

    :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

    确定