JavaScript replace() if string found between startIndex and endIndex as substring() does

Viewed 560

I have some HTML in my DOM and I want to replace some strings in it, but only if that was not already replaced or that is not a TAG.

All that is based on an Array that contains the string I want to find and the new string I want this to be replace with.

Work in progress: https://jsfiddle.net/u2Lyaab1/23/

UPDATE: The HTML markup is just for simplicity written with ULs in the sample code, BUT it can contain different tags, event different nesting levels

Basically the desiredReplcement works nice (except that it looks in tags too), but I want that to happen on the DOM, not the new string because I want to maintain any other HTML markup in the DOM.

SNIPPET:

var list = [{
    original: 'This is',
    new: 'New this is'
  },
  {
    original: 'A list',
    new: 'New A list'
  },
  {
    original: 'And I want',
    new: 'New And I want'
  },
  {
    original: 'To wrap',
    new: 'New To wrap'
  },
  {
    original: 'li',
    new: 'bold'
  },
  {
    original: 'This',
    new: 'New This'
  },
  {
    original: 'strong',
    new: 'bold'
  },  {
original: 'This is another random tag',
new: 'This is another random tag that should be bold'
  }

];


var div = $('.wrap');
var htmlString = div.html();
var index = 0;
list.forEach(function(item, index) {

  console.log(index + ' Should replace: "' + item.original + '" with "' + item.new + '"');

  //I know that there is something here, but not sure what
  index = htmlString.indexOf(item.original);
  var expressionLength = index + item.original.length;
  var substring = htmlString.substring(index, expressionLength);
  var desiredReplcement = substring.replace(item.original, '<strong>' + item.new + '</strong>');
  console.log('index', index);
  console.log('substring', substring);
  console.log('desiredReplcement', desiredReplcement);

  //Current implementation in replace looks in the full div, but I just want to replace in the substring mathced above;
  var replacement = '<strong>' + item.new + '</strong>';
  var newHTML = div.html().replace(item.original, replacement);
  div.html(newHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <ul>
    <li>This is</li>
    <li>A list</li>
    <li>And I want</li>
    <li>This should not be bold</li>
    <li>To wrap</li>
    <li>This</li>
    <li>strong</li>
    <li>li</li>
  </ul>
<span><p><em>This is another random tag</em></p></span>
</div>

4 Answers

The following code will not replace tags and will do only one replacement for one text node (if there is any match). It looks through the whole structure in a recursive manner and checks the text of the elements.(and it uses the same list you described in your question)

Requirements:

  1. Replace text just in case of exact match => use === instead of indexOf

  2. Replace text only once => remove item from list after use

    var div = $('.wrap');
    
    function substitute(htmlElement, substituteStrings){
      var childrenElements = htmlElement.children;
      if(childrenElements.length !== 0){
        for (let i=0;i<childrenElements.length;i++){
            substitute(childrenElements[i], substituteStrings);
        }
      } else {
        var htmlString = htmlElement.innerText;
        substituteStrings.some(function(item){
            if(htmlString == item.original){
                htmlElement.innerHTML = htmlString.replace(item.original, '<strong>' + item.new + '</strong>');
                substituteStrings.splice(index,1);
                return true;
            }
        });
      }
    }
    substitute(div[0],list);
    

I don't think that jQuery is necessary here.

First, you want to retrieve your container, which in your case will be the .wrap div.

var container = document.querySelector('.wrap');

Then you want to create a recursive function that will loop through an array to search and replace the data provided.

function replacement(containers, data){

    if(!data || !data.length)
        return;

    for(let i=0; i<containers.length; i++){

        var container = containers[i];

        // Trigger the recursion on the childrens of the current container
        if(container.children.length)
            replacement(container.children, data);

        // Perform the replacement on the actual container
        for(let j=0; j<data.length; j++){
            var index = container.textContent.indexOf(data[j].original);

            // Data not found
            if(index === -1)
                continue;

            // Remove the data from the list
            var replace = data.splice(j, 1)[0];
            container.innerHTML = container.innerHTML.replace(replace.original, '<strong>' + replace.new + '</strong>');

            // Lower the j by 1 since the data array length has been updated
            j--;

            // Only want to perform one rule
            break;

        }
    }
}

Demo: https://jsfiddle.net/u2Lyaab1/25/

The basic idea is to use recursion to search through every nested node in the parent node.

My answer (partial answer) has the same results as Zsolt V's, but is a little less elegant.

Zsolt V has checked child nodes, and it can therefore work with innerHTML by using HTML tags. I on the other hand have checked if a node is a textNode, and have built the replacement nodes using the DOM (pure DOM solution) and nodes' textContent property.

var list = [{
    original: 'This is',
    new: 'New this is'
  }, {
    original: 'A list',
    new: 'New A list'
  }, {
    original: 'And I want',
    new: 'New And I want'
  }, {
    original: 'To wrap',
    new: 'New To wrap'
  }, {
    original: 'li',
    new: 'bold'
  }, {
    original: 'This',
    new: 'New This'
  }, {
    original: 'strong',
    new: 'bold'
  }, {
    original: 'This is another random tag',
    new: 'This is another random tag that should be bold'
  }

];


//I want for each expression in this array, to find that expression in array, replace-it and make-it bold with a <strong> tag.

var div = document.getElementsByClassName("wrap")[0];

function processNode(node) {
  if (node.nodeName === "#text") {
    list.forEach(function(item, index) {
      if (node.parentNode && node.textContent.indexOf(item.original) > -1) {
        //node.textContent = node.textContent.replace(item.original, item.new);

        let untouched = node.textContent.split(item.original);
        console.log(untouched);
        for (let i = untouched.length - 1; i > 0; i--) {
          untouched.splice(i, 0, item.new);
        }
        console.log(untouched);
        for (let i = 0, l = untouched.length; i < l; i++) {
          let newNode = i % 2 === 0 ? document.createTextNode("") : document.createElement("strong");
          newNode.textContent = untouched[i];
          node.parentNode.appendChild(newNode);
        }
        node.parentNode.removeChild(node);
      }
    })
  } else {
    node.childNodes.forEach(function(child, index) {
      processNode(child);
    })
  }
}

processNode(div)

JSFiddle (partial answer)

You write in the comments on Zsolt V's answer that:

but as you can see, the last sentence is replaced differently than the expected in the list

However, the problem is not with the code, but with the ordering of the list array. The problem is that you have replacements that work within one another, i.e. acting on list[7], with list[0]:

"This is another random tag" (list[7] before)

-> "New this is another random tag" (list[7] after applying changes from list[0])

You need to be mindful of the ordering.

In fact, I moved the last item in the list array to the top, and the results are as you've asked for.

var list = [{
    original: 'This is another random tag',
    new: 'This is another random tag that should be bold'
  }, {
    original: 'This is',
    new: 'New this is'
  }, {
    original: 'A list',
    new: 'New A list'
  }, {
    original: 'And I want',
    new: 'New And I want'
  }, {
    original: 'To wrap',
    new: 'New To wrap'
  }, {
    original: 'li',
    new: 'bold'
  }, {
    original: 'This',
    new: 'New This'
  }, {
    original: 'strong',
    new: 'bold'
  }

];

JSFiddle (full answer)

Related