Please tell me how to implement a javascript function that runs through the document body from beginning to end and replaces all odd occurrences of the search string str with str1 , and all even occurrences of str with str2 .

Theoretically, I understand that you need to start a certain cycle from the beginning to the end of the page, and write in this cycle something like this:

 count = count +1; 

If count is odd, then replace the current element with str1
If count is even, then replace the current element with str2

What command can I use for this?

Closed due to the fact that off-topic participants Vladyslav Matviienko , BogolyubskiyAlexey , Wolkodav , romeo , Athari 6 Nov '15 at 13:21 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Questionnaires are forbidden on Stack Overflow in Russian . To get an answer, rephrase your question so that it can be given an unambiguously correct answer." - Vladyslav Matviienko, BogolyubskiyAlexey, Wolkodav, romeo
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    In fact, I was somewhat quick to answer. It would be better to break the original question into two: about the replacement of the line and about working with the contents of the page. - Dmitriy Simushev

3 answers 3

If on pure JavaScript, something like this (not tested)

 function replaceWithSelect(pattern, oddStr, evenStr) { var items = document.getElementsByTagName("*"), // выбираем все теги oddFound = false, rx = new RegExp((pattern + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"), "g"); children, node; for (var ix = items.length; ix--;) { // обходим все теги children = items[ix].childNodes; for (var iy = children.length; iy--) { // перебираем все узлы node = children[iy]; if (3 == node.nodeType) { // если узел текстовый node.nodeValue = node.nodeValue.replace(rx, function() { oddFound = !oddFound; return oddFound ? oddStr : evenStr; }); } } } } replaceWithSelect(str, str1, str2); 
  • Thanks for the answer :) I wanted to clarify: the str parameter in the string node.nodeValue = node.nodeValue.replace (str, substitution); anywhere not previously announced. Or do you need to drive node.nodeValue to str before performing the substitution? - Alexey
  • @ Aleksey This is the string we are looking for. It must be specified before calling the given code. For example, you can wrap this code in the function function (str, str1, str2) {} . Perhaps I will correct the answer - tutankhamun
  • @ Alexey ... especially since the error crept in the replacement logic - tutankhamun
  • +1 - I liked the replacement of strings by a regular expression and a function in replace - which allows us to do without a loop. Again - the reputation is rounded. Hope not for long. - Igor

You need a function to check for sub-lines. You will do .indexOf

 str.indexOf(subStr) //Вернет 0 или больше если под-строка найдена, и -1 если нет ни одного вхождения. 

To replace a substring, use .replace

 str = str.replace(subStr, str1); //заменит первое вхождение подстроки (только первое, остальные останутся не тронутами) 

As you have already written, you need an entry count. Start the while and, depending on the counter, call replace using str1 or str2 .

I hope it is clear explained, it is not always possible to explain what would be clear to everyone))

  • Who clearly thinks - clearly states: str = str.replace(subStr, (count++ % 2 == 0)? str1 : str2); - Igor
  • Tell me, please, let the while loop for what? What in this case are signs of the start and stop of the cycle? - Alexey
  • In my vision, while runs by the condition str.indexOf (subStr)> = 0, that is, execute the loop as long as there is at least one sub-string. Below in another answer you brought the best option for the function. - walik

If right in the forehead, then you can take the entire text of the document as a replacement. I think this option is the fastest. Here is an example of replacing even / odd matches and replacing even / odd matches of pairs (for example HTML / XML tags):

 /* Замена чет/нечет */ var i = 0; // итератор document.documentElement.innerHTML = document.documentElement.innerHTML.replace(/Заголовок\s\d/g, function(){return (i++ % 2) ? 'Четный' : 'Нечетный'}); /* Пример парных замен, например HTML тегов. Т.к. они парные в большинстве своем, то меняем и закрывающие теги. С случае попадания в выборку не парных тегов, будут не правильные результаты и в таком случае надо рабвивать на 2 вызова replace() и менять сначала открывающие теги, а потом закрывающие */ i = 1; // обнуляем итератор document.documentElement.innerHTML = document.documentElement.innerHTML.replace(/h\d/g, function(){return (++i % 4 >= 2) ? 'h1' : 'h6'}); 
 <h1>Заголовок 1</h1> <h2>Заголовок 2</h2> <h3>Заголовок 3</h3> <h4>Заголовок 4</h4> <h5>Заголовок 5</h5> <h6>Заголовок 6</h6>