L
L
lagudal2020-02-14 13:46:15
JavaScript
lagudal, 2020-02-14 13:46:15

How to find and replace multiple occurrences in text with one script?

there is such a construction that allows you to find and replace a certain occurrence in html - a word or a sentence - with another one on the fly.

$("body").children().each(function() {
    $(this).html($(this).html().replace(/old text/g,"new text"));
  });

Now, if such substitutions need to be made about a dozen - i.e. there are 10 occurrences that need to be replaced with 10 new ones, while of course you need a clear correspondence, what will change to what.
How to solve this problem in less than 10 times to write this construction?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-02-14
@lagudal

const replacements = [
  [ 'вот это надо заменить', 'вот на это' ],
  [ 'а это заменить', 'на вот это' ],
];

$elements.html((i, html) => {
  return replacements.reduce((acc, n) => acc.replace(RegExp(n[0], 'g'), n[1]), html);
});

A
Alexander Talalaev, 2020-02-14
@neuotq

The easiest thing is not to sweat.
Something like this, I wrote without testing, but I hope the idea is understandable

const replacePairs= {'было1': 'стало1', 'было2': 'стало2', 'было3': 'стало3'};
$("body").children().each(function() {
  let currentNode = $(this);
  for (const pair in replacePairs) {
     currentNode.html(currentNode.html().replace(/`${pair}`/g, `${replacePairs[pair]}`));
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question