Home > database >  Replace string and repeat for each variable Javascript
Replace string and repeat for each variable Javascript

Time:08-14


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" ></div>';      
    jQuery(GetListing).prepend(AddLabel);
    }
    else{}
</script>

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


Please Help!

CodePudding user response:

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);
  • Related