Javascript find part of the text and replace (with variable)

Asked

Viewed 113 times

1

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

In the gallery of larger photos, I just need to pass the value start:nºda foto, for it to start from the clicked photo. photo number is the id that is passed by the function galeria(this.id).

Then I made a str.replace to sub-stage the start:0 (which is how it starts), for the start:id, which is the past value, the problem that only works once, after it changes the start:0 to the start:id, I don’t know how to make him find the last start:id to 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>

2 answers

1

Looking at his code, he was trying to replace the string that would be the innerHTML of the element with id="gallery".

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

I suggest just changing the value of the data-uk-slideshow attribute accordingly:

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

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>

A regex \d+ will only take the number and replace, in case, the ids.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.