How in JavaScript with replace replace in the <a> tag the content of the data parameter with the variable v1 , and the content of the span with v2 ? In other words, %name1 on 'Π‘Ρ‚ΠΈΡ€Π°Π»ΡŒΠ½Π°Ρ машина' , %name2 on 'Вятка' . At the same time creating a clone of the html code by writing it into a variable:

 var v1 = 'Π‘Ρ‚ΠΈΡ€Π°Π»ΡŒΠ½Π°Ρ машина'; var v2 = 'Вятка'; 

html:

 <h3 class="category"> <a class="link" href="#" data="%name1"> <span class="cat-title">%name2</span> </a> </h3> 

Thank!

  • Isn't it easier to use the features of the jQuery library? - player0k
  • @ player0k No, you need to JavaScript - Pavel

2 answers 2

 var v1 = 'Π‘Ρ‚ΠΈΡ€Π°Π»ΡŒΠ½Π°Ρ машина', v2 = 'Вятка', wr = document.querySelector('#wrapper'); wr.innerHTML = wr.innerHTML.replace(/%name(\d+)/ig, (f, n) => { // f - всё совпадСниС, Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ %name1 // n - Π½ΠΎΠΌΠ΅Ρ€, Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ 1 switch(+n){ case 1: // %name1 return v1; break; case 2: // %name2 return v2; break; default: return f; } }); 
 Before: <br /> <h3 class="category"> <a class="link" href="#" data="%name1"> <span class="cat-title">%name2</span> </a> </h3> <hr />After: <br /> <div id='wrapper'> <h3 class="category"> <a class="link" href="#" data="%name1"> <span class="cat-title">%name2</span> </a> </h3> </div> 

    Write a function

     function ReplaceText(v1, v2, str){ var newStr=str.replace('%name1', v1); var newStr=newStr.replace('%name2', v2); return newStr; } 

    And then call the function

     var new=ReplaceText('Π‘Ρ‚ΠΈΡ€Π°Π»ΡŒΠ½Π°Ρ машина', 'Вятка', '<h3 class="category"><a class="link" href="#" data="%name1"><span class="cat-title">%name2</span></a></h3>'); 
    • the function doesn't work - Pavel
    • var new ? Seriously? - Grundy
    • I wrote for example - Diefair
    • new - can not be used as an identifier, because the reserved word, to learn more: ph4.ru/javascript_reserv.php new - 7: 2 in the table. - user207618