Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace string and repeat for each variable Javascript

I have a variable with this content

var PropertysIds = "1234,2345,3456"

What I need is that for each id I have separated by "," replace "REPLACEHERE" in the following content.

<script type="text/javascript">
    var GetListing = document.querySelector('.listing_wrapper[data-listid="REPLACEHERE"]');
    if ( GetListing ) { 
    var AddLabel = '<div title="Casa Segura" class="casa_segura2"></div>';      
    jQuery(GetListing).prepend(AddLabel);
    }
    else{}
</script>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The end result should be that script repeated three times but with the string "REPLACEHERE" replaced by each ","

Please Help!

>Solution :

You could use split to make the string an array, and then map each to a selector. Concatenate those selectors with a comma, and pass it to jQuery:

jQuery(
    PropertysIds.split(',')
                .map(id => `.listing_wrapper[data-listid="${id}"]`)
                .join(',')
).prepend(AddLabel);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading