如何将复制与括号匹配

wlsrxk51  于 2021-09-23  发布在  Java
关注(0)|答案(3)|浏览(237)

我试图在页面上找到一个特定的产品名称,如果匹配,那么我想在这个名称的末尾添加“-10%折扣”。
我的问题是在括号中的产品名称末尾“(1+1)”如何将其包含在变量中 findCopy 因此,我的结果将是:“产品名称(1+1)-10%折扣”

var findCopy = 'Product Name';
// The below is what I'm trying to achieve to get
// var findCopy = 'Product Name (1+1)';
var targetThis = document.querySelector('.copy');
targetThis.innerText = targetThis.textContent.replace(new RegExp(findCopy), findCopy + '  - 10% Discount');
<p class="copy">Product Name (1+1)</p>
yeotifhr

yeotifhr1#

主要基于alireza ahmadi解决方案,但允许您同时更改多个产品:

var findCopy = 'Product Name';
        // The below is what I'm trying to achieve to get
        // var findCopy = 'Product Name (1+1)';
var targetThis = [...document.querySelectorAll('.copy')].filter(tag => tag.textContent.includes(findCopy))

targetThis.forEach(el => el.innerText = el.textContent + '  - 10% Discount');
<ol>
<li class="copy">Product Name (1+1)</li>
<li class="copy">Product (1+1)</li>
<li class="copy">Product Name</li>
<li class="copy">(1+1) Product Name</li>
<li class="copy">Potato</li>
</ol>
ryoqjall

ryoqjall2#

你知道产品名称吗 Product Name (1+1) ,因此需要找到具有相同值的标记,然后将其追加 - 10% Discount ```
var findCopy = 'Product Name (1+1)';
// The below is what I'm trying to achieve to get
// var findCopy = 'Product Name (1+1)';
var targetThis = [...document.querySelectorAll('.copy')].filter(tag => tag.textContent.includes(findCopy))[0]

targetThis.innerText = targetThis.textContent + ' - 10% Discount';

    var array = document.querySelectorAll('.copy');
    var targetThis;
    for (var i = 0; i < array.length; i++) {
        if (array[i].textContent.includes(findCopy))
            targetThis = array[i];
    }

    targetThis.innerText = targetThis.textContent + '  - 10% Discount';
erhoui1w

erhoui1w3#

我不知道您是否可以使用jquery。在这里,我使用jquery实现了一个解决方案。当然,它适用于多种情况
并改变它们
html:

<div class="new">
        <p>
            product Name 1
        </p>
        <p>
            product Name 2
        </p>
        <p>
            product Name 3
        </p>
        <p>
            product Name 1 abcde
        </p>
    </div>
<button onclick="test('product Name 1')">test</button>

js代码:

function test(string) {         
                $("p:contains('" + string + "')").each(function () {
                    var sHtml = $(this).html();
                    $(this).html(sHtml + " - 10% Discount");
                })
        }

最后,它将更改如下内容:
产品名称1-10%折扣
产品名称2
产品名称3
产品名称1 de-10%折扣

相关问题