inaz inaz - 3 months ago 12
CSS Question

how to extract substring before a specified character (comma)

I am trying to extract everything before the ',' comma. and replace it with a same name image. How do i do this in javascript or jquery? I tried this but not working for the first and the last string
here is my codes:

<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('<img src="/images/'+ arrayOfStrings.join('.png" /><img src="/images/') + '/>');
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>

Answer

When you use a split method you get an array of strings in return. But you are directly joining the array with the html tags. You can try something like below in which I am joining the string at a particular index of the array of strings.

<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('<img src="/images/'+ arrayOfStrings[1].join('.png" /><img src="/images/') + '/>');
}
</script>
</head>
<body>
<div  class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>   
</body>
</html>`

If you want to display all images in the array of strings, you can traverse through all array like this.

    <html>
        <head>
        <script>
        function splitString(stringToSplit, separator) {
        var arrayOfStrings = stringToSplit.split(separator);

        var imagesHtml = '';
        for(var i = 0; i < arrayOfStrings.length; i++){
            if(arrayOfStrings[i] !== ''){
               imagesHtml = imagesHtml + '<img src="/images/' + arrayOfStrings[i] + '.png" />'
            }
        }
        $(".slidepop").html(imagesHtml);
}
        </script>
        </head>
        <body>
        <div  class="slidepop">
        <script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
        </div>   
        </body>
        </html>`
Comments