Search code examples
javascriptparentheses

How to match copy with parentheses Javascript


I'm trying to find a specific Product Name on a page, and if this matches then I want to add " - 10% Discount" at the end of this name.

The issue I have is at the end of the Product Name I have in parentheses "(1+1)" how can I include this in the variable findCopy so my outcome will be: "Product Name (1+1) - 10% Discount"

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>


Solution

  • You know the product name like Product Name (1+1), so you need to find the tag has the same value and then append it - 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';
        <p class="copy">Product Name (1+1)</p>

    Update without spread operator:

            var findCopy = 'Product Name (1+1)';
            // The below is what I'm trying to achieve to get
            // var findCopy = 'Product Name (1+1)';
    
            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';
     <p class="copy">Product Name (1+1)</p>