Javascript find part of text and replace (with variable)

1

I have a photo slideshow that when you click on the photo it opens the larger photos.

In the larger photo gallery, I only need to pass start:nºda foto so that it starts from the clicked photo. photo number is the id that is passed by the galeria(this.id) function.

Then I made a str.replace to subtitute the start:0 (that is how it starts), to start:id , which is the value passed, the problem that only works once, after it changes the start:0 for start:id , I do not know how to make it find the last start:id for the new start:id

<ul id="galeriamenor">
<li><a href="#galeria" id="1" onclick="galeria(this.id)"><img src="foto1"></a></li>
<li><a href="#galeria" id="2" onclick="galeria(this.id)"><img src="foto2"></a></li>
<li><a href="#galeria" id="3" onclick="galeria(this.id)"><img src="foto3"></a></li>
<li><a href="#galeria" id="4" onclick="galeria(this.id)"><img src="foto4"></a></li>
</ul>

<ul id="galeria" data-uk-slideshow="{start:0}">
<li><img src="maior/foto1"></li>
<li><img src="maior/foto2"></li>
<li><img src="maior/foto3"></li>
<li><img src="maior/foto4"></li>
</ul>

<script>
 function galeria(id) {
  var str = document.getElementById("galeria").innerHTML; 
  var res = str.replace("start:0", "start:"+id);
  document.getElementById("galeria").innerHTML = res;
 }
</script>
    
asked by anonymous 17.05.2018 / 17:47

2 answers

1

You can use a regex in your replace:

function galeria(id) {
   var str = document.getElementById("galeria").innerHTML; 
   var res = str.replace(/\d+/, id);
   document.getElementById("galeria").innerHTML = res;
}
<select onChange="galeria(this.value)">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="10">10</option>
</select>
<br>
<div id="galeria">start:0</div>

The regex \d+ will only take the number and replace, in this case, the id s.

    
17.05.2018 / 17:54
1

Looking at your code, I was trying to make a replace in the string that would be the innerHTML of the element with id="gallery".

But the innerHTML is the internal content, and it did not contain the string "start", but it exists in the element itself, as content of an attribute (data-uk-slideshow="{start: 0}") >

I suggest only changing the value of the data-uk-slideshow attribute as follows:

<script>
 function galeria(id) {
  var eGaleria = document.getElementById("galeria"); 
  eGaleria.setAttribute("data-uk-slideshow", "{start:"+id+"}");
 }
</script>
    
18.05.2018 / 01:56