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

I have HTML in my DOM and I want to replace some lines in it, but only if it has not been replaced or it is not a TAG.

Everything based on an array that contains the string I want to find and the new string, I want this to be replaced.

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

UPDATE: HTML markup is designed for simplicity, written using UL in the code sample, BUT may contain different tags, different levels of event nesting

It desiredReplcementworks well in principle (except that it also looks in tags), but I want this to happen on the DOM, and not on a new line, because I want to support 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>
Run codeHide result
+6
source share
4 answers

I don't think jQuery is needed here.

First you want to get your container, which in your case will be a .wrapdiv.

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

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

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/

+1
source

div <div class="wrap">...</div>, htmlString html .

, , .

.

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'
  }
  
];

var div = document.getElementsByClassName('wrap')[0].getElementsByTagName('li');  // Getting all <li> elements within <div class="wrap">

Array.prototype.forEach.call(div, function(li, x){  // Borrowing Array forEach method to be used on HTMLCollection

    list.forEach(function(value, i){                // Looping through list
        if (value.original === li.innerHTML)        // if list[i]['original'] === li[x].innerHTML
            li.innerHTML = '<strong>' + value.new + '</strong>';
            
    });
    
    
});
<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>
</div>
Hide result
+3

node ( - ). . ( , )

:

  • = > === indexOf

  • = >

    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);
    
+1

- node node.

( ) , Zsolt V, .

Zsolt V , innerHTML HTML. , , , node Node, , DOM ( DOM) textContent .

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 ( )

Zsolt V , :

, , ,

, list. , , , .. list[7], list[0]:

" " (list[7] before)

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

You must remember about the order.

In fact, I moved the last element to the array listat the top, and the results were the same as you requested.

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)

+1
source

All Articles