Slicing the last two characters off a jquery variable

51 views Asked by At

So i found a script that renders an image based on the selection made in a drop down.

however this script or something somewhere else is appending these |0 characters to the end of the image source.

this is the script in jquery

<script type="text/javascript">

 jQuery(document).ready(function($){

var dropdown = '#input_1_10'; // the ID of your dropdown feild
var imageContainer = '#swatches'; // the id of the div which contains your image

$(dropdown).change(function(){
    var value = $(this).val();
    jQuery(imageContainer).html('<img src="'+value+'" alt="" />'); 
});

});

   </script>

This is what i see from the inspect element window

<img src="http://www.whiskey3defensesolutions.com/wp-content/uploads/2016/11/1-Arctic-White.jpg|0" alt="">

This happens on every single image i try to link with the drop down options

so what i want to do is slice off the |0 but i can't figure out how

This is on a wordpress website running Woocommerce, Woocommerce Gravity forms Add-on and Gravity forms plugin.

3

There are 3 answers

3
divHelper11 On

Just try using slice js function. It cuts the string however you want it. We will use it to cut the last 2 characters of your string.

<script type="text/javascript">

     jQuery(document).ready(function($){

    var dropdown = '#input_1_10'; // the ID of your dropdown feild
    var imageContainer = '#swatches'; // the id of the div which contains your image

    $(dropdown).change(function(){
        var value = $(this).val();
        value = value.slice(0,-2)  //<--this should be cutting it
        jQuery(imageContainer).html('<img src="'+value+'" alt="" />'); 
    });

    });

</script>
4
t4dohx On

You can use .split("|") to split string.

$(document).ready(function($){
  var dropdown = '#input_1_10'; // the ID of your dropdown feild
  var imageContainer = '#swatches'; // the id of the div which contains your image
  $(dropdown).change(function(){  
    var value = $(this).val().split("|")[0];   
    $(imageContainer).html('<img src="'+value+'" alt="" />'); 
  });    
});
0
BrunoLM On

You could also use Regex to replace text

var url = 'http://.../1-Arctic-White.jpg|0';

var newUrl = url.replace(/\|.*?$/, '');

console.log(newUrl);