-5

I have 5 paragraphs:

<input id="ed_ru" type="hidden" value="<p>1 paragraph</p><br>
  <p>213123123123</p>
  <p>213123123123</p>
  <p>213123123123</p>
  <p>213123123123</p>
">

I need paste: {{231111}} in 3 paragraph, and skip 1 and paste in 5 paragraph and e.t.c. How I can do it?

Now I have:

jQuery('#ed_ru').val(jQuery('#ed_ru').val() + '{{'+id+'}} ');

I need get result:

    <input id="ed_ru" type="hidden" value="<p>1 paragraph</p><br>
     <p>213123123123</p>
     <p>{{231111}}213123123123</p>
     <p>213123123123</p>
     <p>{{231111}}213123123123</p>
    ">
Foxer
  • 1
  • 2
    I dont even think that is valid HTML5. Why would you want to have markup within the value of an input field? Also your jquery code makes no sense, and in general your question is very confusing. – N. Ivanov Mar 27 '18 at 14:06
  • Also don't use regex to parse html. – user3483203 Mar 27 '18 at 14:14

1 Answers1

0

If I get you right you want to prefix the content of every even (begining at 0) occurrence of a paragraph with the string "{{231111}}" (but skip the first).

So you could split the string into an array, prefix like you need and then join the array back into a string. This is how it would look like:

let newStr = $('#ed_ru')
  .val()
  .split("<p>")
  .map((el,it) => { 
    return (it !== 1 && it % 2 == 1 && el !== '') ? '{{231111}}' + el : el
  })
  .join('<p>');

$('#ed_ru').val(newStr);

console.log(newStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="ed_ru" value="<p>1 paragraph</p><br><p>213123123123</p><p>213123123123</p><p>213123123123</p><p>213123123123</p>">

NOTE: the condition it !== 1 && it % 2 == 1 && el !== '' needs to cover the first element which is '' due to the .split()

Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
  • I get duplicates, if send request again. How I can check, if already exists {{}} in paragraph, and if exists skip? – Foxer Mar 27 '18 at 14:42
  • `$('#ed_ru').val().contains('{{231111}}')` gives you true if `{{231111}}` exist within the string, so check on that and skip in case. And please also read docs on JavaScript, this are basics and SO is not here to solve the problem for you. Mark this question as correct if it helps on your problem so this gets resolved – Kristianmitk Mar 27 '18 at 14:49
  • This is help me, but I need check with regex ``{{id}}``id = number. Snd how I can skip in map this? – Foxer Mar 27 '18 at 14:51